如何使用Java反射调用超类方法 [英] How to call a superclass method using Java reflection
本文介绍了如何使用Java反射调用超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个班级。
public class A {
public Object method() {...}
}
public class B extends A {
@Override
public Object method() {...}
}
我有一个B的实例。如何从b调用A.method()?基本上,与从B调用super.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);
但上面的代码仍然会调用B.method()
But the above code will still invoke B.method()
推荐答案
如果您使用的是JDK7,可以使用MethodHandle来实现此目的:
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";
}
}
这篇关于如何使用Java反射调用超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文