问题
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";
}
}
回答1:
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>());
回答2:
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 only work for a static (class) method, but execute is a non-static (instance) method.
You need an actual instance of TestFunction to invoke the method on, or you need to make the method static.
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.
来源:https://stackoverflow.com/questions/13336057/java-reflection-object-is-not-an-instance-of-declaring-class