通过反射或其他方式覆盖 java final 方法? [英] override java final methods via reflection or other means?

查看:26
本文介绍了通过反射或其他方式覆盖 java final 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是在尝试编写测试用例时出现的.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 对象.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() 设置为非最终的?或者我应该如何进行测试?

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 final 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆