Java Reflection: “java.lang.NoSuchMethodException”

2019-03-07 04:03发布

问题:

I am trying to get the method from another class using reflection, but for some reason it keeps on giving me a no such method exception. These are the classes im using:

ScriptTable class:

for(Class<?> script: Scripts) {
        System.out.println(script.getName());
        try {
            Method c = script.getMethod("scriptInfo()", script);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

DummyScript class

    public String[] scriptInfo() {
    String[] ScriptInfo = {"DummyScript", "Chris", "Does nothing atm"};
    return ScriptInfo;
}

回答1:

This is your problem:

script.getMethod("scriptInfo()", script);

change it to:

script.getMethod("scriptInfo");

and look here to see why:

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getMethod%28java.lang.String,%20java.lang.Class...%29