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()
.
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.
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.
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.
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.
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"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With