How to call a superclass method using Java reflection

Ted picture Ted · Mar 23, 2011 · Viewed 44.9k times · Source

I have two classes:

public class A {
    public Object method() {...}
}

public class B extends A {
    @Override
    public Object method() {...}
}

I have an instance of B. How do I call A.method() from b? Basically, the same effect as calling super.method() from B.

B b = new B();
Class<?> superclass = b.getClass().getSuperclass();
Method method = superclass.getMethod("method", ArrayUtils.EMPTY_CLASS_ARRAY);
Object value = method.invoke(obj, ArrayUtils.EMPTY_OBJECT_ARRAY);

But the above code will still invoke B.method().

Answer

java4script picture java4script · Mar 28, 2013

If you are using JDK7, you can use MethodHandle to achieve this:

public class Test extends Base {
  public static void main(String[] args) throws Throwable {
    MethodHandle h1 = MethodHandles.lookup().findSpecial(Base.class, "toString",
        MethodType.methodType(String.class),
        Test.class);
    MethodHandle h2 = MethodHandles.lookup().findSpecial(Object.class, "toString",
        MethodType.methodType(String.class),
        Test.class);
    System.out.println(h1.invoke(new Test()));   // outputs Base
    System.out.println(h2.invoke(new Test()));   // outputs Base
  }

  @Override
  public String toString() {
    return "Test";
  }

}

class Base {
  @Override
  public String toString() {
    return "Base";
  }
}