61

This question is being asked everywhere on Google but I'm still having trouble with it. Here is what I'm trying to do. So like my title states, I'm getting an 'object is not an instance of declaring class' error. Any ideas? Thanks!

Main.java

Class<?> base = Class.forName("server.functions.TestFunction");
Method serverMethod = base.getMethod("execute", HashMap.class);
serverMethod.invoke(base, new HashMap<String, String>());

TestFunction.java

package server.functions;

import java.util.HashMap;
import java.util.Map;

import server.*;

public class TestFunction extends ServerBase {

    public String execute(HashMap<String, String> params)
    {
        return "Test function successfully called";
    }
}

2 Answers 2

84

You're invoking the method with the class, but you need an instance of it. Try this:

serverMethod.invoke(base.newInstance(), new HashMap<String, String>());
Sign up to request clarification or add additional context in comments.

Comments

22

You are trying to invoke the execute method on the object base, which is actually a Class object returned by your Class.forName() call.

This would work for a static (class) method - but execute is a non-static (instance) method.

(It would also work for calling an instance method of an object of type Class - but that's not what you are trying to achieve here!)

You need an actual instance of TestFunction to invoke the method on, or you need to make the method static.

When invoking a static method by reflection, the first argument to invoke() is ignored, so it is conventional to set it to null, which clarifies the fact that there's no instance involved.

Although your current example method would do the same thing for any TestFunction object, in general an instance method could produce a different result for each object - so the .invoke() reflection method needs to know which object to run the method on.

6 Comments

Yes indeed, as described in the JavaDoc.
Thanks for the detailed explanation. I wish I could select multiple correct answers for this question.
@tkcsam - the idea is you select the BEST correct answer ... in your opinion.
@tkcsam - If you mean ... for rewarding other answers than the one that you accepted, then ... yes, that it true.
"This would only work for a static (class) method" - that's not true, it would work only for a method of class java.lang.Class. Conversely, to invoke static methods one has to pass obj = null to invoke.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.