Java Reflection-对象不是声明类的实例


问题内容

这个问题在Google上到处都有,但我仍然遇到问题。这就是我想要做的。因此,就像标题状态一样,我遇到了“对象不是声明类的实例”错误。有任何想法吗?谢谢!

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";
    }
}

问题答案:

您正在使用该类调用该方法,但需要一个实例。试试这个:

serverMethod.invoke(base.newInstance(), new HashMap<String, String>());