所以我在下面有以下代码并在其他地方调用了Operators Op = new Operators()
。但是,我在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;
}
}
编辑。引用的行是return Operators.class.getMethod(s, inputTypes);
方法中的getMethod
。
答案 0 :(得分:3)
一旦我理解了你想要做的事情,它可能会让我更好地了解如何帮助你,但乍一看,这可能是它:
inputTypes-array
包含两个Float.class-es
,但您的方法使用基本类型。带有大写字母的Float
与float
小写不同,因此我希望NoSuchMethodException
。
答案 1 :(得分:0)
您还可以通过更改类来避免声明输入参数类型,您可以在构造函数外部执行此操作:
public class Operators {
static final String ADD = "+";
static final String MULTIPLY = "*";
static final String SUBTRACT = "-";
static final String DIVIDE = "/";
private static Method[] methods;
static Map<String, Method> methodsMap = new HashMap<String, Method>();
static {
methods = Operators.class.getMethods();
try {
methodsMap.put(ADD, getMethod("add"));
methodsMap.put(MULTIPLY, getMethod("multiply"));
methodsMap.put(SUBTRACT, getMethod("subtract"));
methodsMap.put(DIVIDE, getMethod("divide"));
} catch (NoSuchMethodException e) {
// handle error
e.printStackTrace();
}
}
static Method getMethod(String s) throws NoSuchMethodException {
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(s))
return method;
}
throw new NoSuchMethodException(s);
}
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;
}
}
你可以使用方法map:
System.out.println(Operators.methodsMap.get("+").invoke(null, 1.0, 1.0));