Search code examples
javareflectionmethodsfinal

override java final methods via reflection or other means?


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(){
  ...
  }
}

my applications will

public class Bar extends Foo{
  public int process(){
    Object value = getX();
    ...
  }
}

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();
    ...
  }
}

Is there a way i can use reflection api to set the getX() to non-final? or how should I go about testing?


Solution

  • 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();
        ...
      }
    }
    

    then, you could override doGetX in BarTest.