16

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();
            }
        }
    }
Community
  • 1
  • 1
warner
  • 167
  • 1
  • 2
  • 7

2 Answers2

23

You need an instance, not the class:

TestMain object = // get TestMain object here
m1.invoke(object);

Or if you mean a static method, supply null as first parameter:

m1.invoke(null);
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
1

m1 needs to be invoked on an instance of the TestMain class, not on the class itself (i.e. on an object created by new TestMain()).

Mat
  • 202,337
  • 40
  • 393
  • 406