我有2节课,比如A&B:
Class A extends B {
public void subClassMthd(){
System.out.println("Hello");
}
}
Class B {
public void printHelloWorld {
System.out.println("Hello");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我使用反射来调用类A上的方法.我还想调用类B中的printHelloWorld方法.
我试过用
Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Method superClassmthd = classAInstance.getClass()
.getSuperclass().getMethod("printHelloWorld", null);
superClassmthd.invoke(classAInstance);
Run Code Online (Sandbox Code Playgroud)
也尝试过
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 );
Run Code Online (Sandbox Code Playgroud)
但它们都不起作用; 他们抛出一个InstantiationException.
我在这做错了什么?
Boh*_*ian 18
试试这个:
Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ");
mthd.invoke(classAInstance)
Run Code Online (Sandbox Code Playgroud)
的差被使用getDeclaredMethod(),它可以获取的方法所有能见度(public,protected,包/默认和private代替)getMethod(),其只得到方法与public能见度.
| 归档时间: |
|
| 查看次数: |
12208 次 |
| 最近记录: |