Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a superclass method using Java reflection

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

like image 790
Ted Avatar asked Mar 23 '11 20:03

Ted


People also ask

How do you call a superclass method in Java?

Use of super() to access superclass constructor To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

Which method gets super class using reflection?

If you can't modify either class, you need to use reflection to use method handles. You need to use invokespecial calls to call super methods which can be done with MethodHandles. The MethodHandles. lookup() method creates a Lookup instance with the caller class and only permits special calls from that class.

How do you do the superclass method?

Call to super() must be first statement in Derived(Student) Class constructor. If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

How do you call the super class method in subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.


1 Answers

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";   } } 
like image 75
java4script Avatar answered Sep 30 '22 13:09

java4script