Possible Duplicate:
Why do I get “object is not an instance of declaring class” when invoking a method using reflection?
When I run the code below, why does it throw this error?
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)
Here's my main class:
package com;
public class TestMain {
private String strName = "abcdefg...";
@SuppressWarnings("unused")
private void display(){
System.out.println(strName);
}
}
And my test class:
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();
}
}
}
This is my modified code, thank you:
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();
}
}
}