Java Reflection - Object is not an instance of declaring class

感情迁移 提交于 2019-12-29 06:34:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!