所以我在下面有下面的代码,其他地方叫Operators Op = new Operators()
。但是,我在getMethod
调用中遇到错误。我承认我并不完全知道如何使用它,并通过阅读其他人的代码来获得这个结果,所以任何帮助都会很棒。谢谢。Class.getMethod不能正常工作
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Operators {
static Map<String, Method> METHODS = new HashMap<String, Method>();
String ADD = "+"; String MULTIPLY = "*"; String SUBTRACT = "-"; String DIVIDE = "/";
private static Class[] inputTypes = {Float.class, Float.class};
Operators() throws NoSuchMethodException, SecurityException {
METHODS.put(ADD, getMethod("add"));
METHODS.put(MULTIPLY, getMethod("multiply"));
METHODS.put(SUBTRACT, getMethod("subtract"));
METHODS.put(DIVIDE, getMethod("divide"));
}
static Method getMethod(String s) throws NoSuchMethodException {
return Operators.class.getMethod(s, inputTypes);
}
public static float add(float x, float y) {
return x+y;
}
public static float multiply(float x, float y) {
return x*y;
}
public static float subtract(float x, float y) {
return x-y;
}
public static float divide(float x, float y) {
return x/y;
}
}
编辑。在getMethod
方法中引用的行是return Operators.class.getMethod(s, inputTypes);
。
你会得到什么错误? –
@GergelyBacso NoSuchMethodException。 –
引用的行是'return Operators.class.getMethod(s,inputTypes);''getMethod'方法内部''。 –