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();
            }
        }
    }
0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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()).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.