Java Reflection - Object is not an instance of declaring class
JavaReflectionJava Problem Overview
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";
}
}
Java Solutions
Solution 1 - Java
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>());
Solution 2 - Java
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.