gpt4 book ai didi

java - 如何在Java函数中转换字符串?

转载 作者:行者123 更新时间:2023-12-01 07:58:17 26 4
gpt4 key购买 nike

我正在尝试创建一个在 Java 中接受 String 和 double 作为参数的函数,如下所示:

public static double calc(String fx, double arg) {
return fx.convertToFunction(arg); // Pseudocode

}

例如,要计算数字(例如 PI)的余弦,代码为:

calc("cos", Math.PI);

函数 calc 必须将“cos”转换为 Math.cos()。

这至少是可能的吗?

最佳答案

您正在寻找的内容称为 Java 中的反射。

看看这个主题: How do I invoke a Java method when given the method name as a string?

如果没有对异常进行必要的检查,您的代码可能如下所示:

//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,...);

关于java - 如何在Java函数中转换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com