是什么原因导致“对象不是声明类的实例”?
2022-09-03 06:01:46
当我运行下面的代码时,为什么它会抛出这个错误?
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.Test.main(Test.java:10)
这是我的主要类:
package com;
public class TestMain {
private String strName = "abcdefg...";
@SuppressWarnings("unused")
private void display(){
System.out.println(strName);
}
}
还有我的测试课:
package com;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
Class<TestMain> tm = null;
try{
tm= TestMain.class;
Method m1 =tm.getDeclaredMethod("display");
m1.setAccessible(true);
m1.invoke(tm);
}catch(Exception e){
e.printStackTrace();
}
}
}
这是我修改的代码,谢谢:
package com;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
TestMain tm =new TestMain();
try{
Method m1 = tm.getClass().getDeclaredMethod("display");
m1.setAccessible(true);
m1.invoke(tm);
}catch(Exception e){
e.printStackTrace();
}
}
}