bur*_*y_5 1 java string function
我正在尝试创建一个在 Java 中接受 String 和 double 作为参数的函数,如下所示:
public static double calc(String fx, double arg) {
return fx.convertToFunction(arg); // Pseudocode
}
Run Code Online (Sandbox Code Playgroud)
例如,要计算数字(例如 PI)的余弦,代码为:
calc("cos", Math.PI);
Run Code Online (Sandbox Code Playgroud)
并且函数 calc 必须将“cos”转换为 Math.cos()。
这至少是可能的吗?
您正在寻找的称为 Java 中的反射。
看一下这个主题: 当以字符串形式给出方法名称时,如何调用 Java 方法?
如果没有必要的异常检查,您的代码可能如下所示:
//assume that you have an Object that you want to invoke the method on
MyObject obj = new MyObject();
//the variable `method` will hold your function
java.lang.reflect.Method method;
//paremters can be provided to identify a specific method among overloaded methods
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
//invoke the method of your object
method.invoke(obj, arg1, arg2,...);
Run Code Online (Sandbox Code Playgroud)