通过反射或其他方式覆盖java最终方法? [英] override java final methods via reflection or other means?
问题描述
在尝试编写测试用例时出现了这个问题。 Foo是框架库中的一个类,我没有源代码访问。
This question arise while trying to write test cases. Foo is a class within the framework library which I dont have source access to.
public class Foo{
public final Object getX(){
...
}
}
我的应用程序将
public class Bar extends Foo{
public int process(){
Object value = getX();
...
}
}
单元测试用例由于其他依赖项,我无法创建Foo对象,因此无法初始化。当值为null时,BarTest抛出空指针。
The unit test case is unable to initalize as I can't create a Foo object due to other dependencies. The BarTest throws a null pointer as value is null.
public class BarTest extends TestCase{
public testProcess(){
Bar bar = new Bar();
int result = bar.process();
...
}
}
有没有办法我可以使用反射api将getX()设置为非final?或者我该如何进行测试?
Is there a way i can use reflection api to set the getX() to non-final? or how should I go about testing?
推荐答案
你可以创建另一个你可以在测试中覆盖的方法:
you could create another method which you could override in your test:
public class Bar extends Foo {
protected Object doGetX() {
return getX();
}
public int process(){
Object value = doGetX();
...
}
}
然后,你可以在BarTest中覆盖doGetX。
then, you could override doGetX in BarTest.
这篇关于通过反射或其他方式覆盖java最终方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!