通过反射或其他方式覆盖java最终方法?
这个问题是在尝试编写测试用例时出现的。 Foo 是框架库中的一个类,我无权访问它的源代码。
public class Foo{
public final Object getX(){
...
}
}
我的应用程序将
public class Bar extends Foo{
public int process(){
Object value = getX();
...
}
}
单元测试用例无法初始化,因为由于其他依赖项我无法创建 Foo 对象。 BarTest 抛出一个空指针,因为值为空。
public class BarTest extends TestCase{
public testProcess(){
Bar bar = new Bar();
int result = bar.process();
...
}
}
有没有办法使用反射 api 将 getX() 设置为非最终? 或者我应该如何进行测试?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为这是谷歌中“覆盖最终方法 java”的最佳结果之一。 我想我会留下我的解决方案。 该类展示了一个使用示例“Bagel”类和免费使用的 javassist 库的简单解决方案:
As this was one of the top results for "override final method java" in google. I thought I would leave my solution. This class shows a simple solution using the example "Bagel" class and a free to use javassist library:
您可以创建另一个可以在测试中重写的方法:
然后,您可以在 BarTest 中重写 doGetX。
you could create another method which you could override in your test:
then, you could override doGetX in BarTest.
Seb 是正确的,只是为了确保您得到问题的答案,而不是在本机代码中执行某些操作(我很确定这行不通)或在运行时修改类的字节码,并创建该类在运行时覆盖该方法,我看不到改变方法“最终性”的方法。 反思在这里对你没有帮助。
Seb is correct, and just to ensure that you get an answer to your question, short of doing something in native code (and I am pretty sure that would not work) or modifying the bytecode of the class at runtime, and creating the class that overrides the method at runtime, I cannot see a way to alter the "finalness" of a method. Reflection will not help you here.
如果您的单元测试用例由于其他依赖项而无法创建 Foo,这可能表明您一开始就没有正确进行单元测试。
单元测试旨在在与生产代码运行相同的环境下进行测试,因此我建议在测试中重新创建相同的生产环境。 否则,您的测试将不完整。
If your unit test case can't create Foo due to other dependencies, that might be a sign that you're not making your unit test right in the first place.
Unit tests are meant to test under the same circumstances a production code would run, so I'd suggest recreating the same production environment inside your tests. Otherwise, your tests wouldn't be complete.
如果
getX()
返回的变量不是final
,您可以使用 单元测试私有方法的最佳方法是什么? 用于更改private
的值通过反射
变量。If the variable returned by
getX()
is notfinal
you can use the technique explained in What’s the best way of unit testing private methods? for changing the value of theprivate
variable throughReflection
.我最终所做的是上述。 它有点难看......詹姆斯的解决方案肯定比这个好得多......
what i did eventually was the above. it is a bit ugly... James solution is definitely much better than this...