java 使用反射调用超类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14455526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invoke Super class methods using Reflection
提问by Vivek
I have 2 classes, say A & B:
我有 2 个班级,比如说 A 和 B:
Class A extends B {
public void subClassMthd(){
System.out.println("Hello");
}
}
Class B {
public void printHelloWorld {
System.out.println("Hello");
}
}
Now, I am using reflection to invoke the methods on Class A. I would also like to invoke the printHelloWorld method present in Class B.
现在,我使用反射来调用 A 类上的方法。我还想调用 B 类中存在的 printHelloWorld 方法。
I tried using
我尝试使用
Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Method superClassmthd = classAInstance.getClass()
.getSuperclass().getMethod("printHelloWorld", null);
superClassmthd.invoke(classAInstance);
Also tried as
也试过
Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Class superClazz = Class.forName(classAInstance.getClass().getSuperclass().getName());
Object superclassInstance = superClazz.newInstance();
Method superClassmthd = superclassInstance.getMethod("printHelloWorld", null);
superClassmthd.invoke(superclassInstance );
But none of them work; they throw an InstantiationException.
但它们都不起作用;他们抛出一个InstantiationException。
What am I doing wrong here?
我在这里做错了什么?
回答by Bohemian
Try this:
试试这个:
Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ");
mthd.invoke(classAInstance)
The difference is using getDeclaredMethod()
, which gets methods of allvisibilities (public
, protected
, package/default and private
) instead of getMethod()
, which only gets methods with public
visibility.
不同之处在于 using getDeclaredMethod()
,它获取所有可见性(public
, protected
, package/default 和private
)的getMethod()
方法,而不是,它只获取具有public
可见性的方法。
回答by NickJ
What is the visibility of the methods you want to call (public, private etc). If you want to see methods which you cannot call directly, you should use getDeclaredMethod().
您要调用的方法的可见性是什么(公共、私有等)。如果要查看不能直接调用的方法,则应使用 getDeclaredMethod()。
Also, what the the constructors of your classes like? InstantiationException indicates that you are having trouble getting an instance of class A (or B).
另外,你的类的构造函数是什么样的?InstantiationException 表示您在获取类 A(或 B)的实例时遇到问题。
I have the following code and it works:
我有以下代码并且它有效:
A.java
一个.java
import java.lang.reflect.Method;
public class A extends B {
public static void main(String[] args) throws Exception {
A classAInstance = new A();
Method mthd = classAInstance.getClass().getSuperclass().getMethod("XYZ", null);
mthd.invoke(classAInstance);
}
}
B.java
B.java
public class B {
public void XYZ() {
System.out.println("done");
}
}