Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes "object is not an instance of declaring class"? [duplicate]

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();
            }
        }
    }
like image 907
warner Avatar asked Sep 13 '11 09:09

warner


2 Answers

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

like image 32
Mat Avatar answered Sep 20 '22 17:09

Mat


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);
like image 94
Sean Patrick Floyd Avatar answered Sep 20 '22 17:09

Sean Patrick Floyd