有没有办法可以将3个函数中的一个fun1
传递给fun3
作为eval
的参数然后进行评估?代码:
public class Pruebas {
public static double fun1(double x){
return x*1;
}
public static double fun2(double x){
return x*2;
}
public static double fun3(double x){
return x*3;
}
public static double eval(funx,double x0){
/* funx at this point i expect it to be fun1, fun2 or fun3 */
double f=funx(x0);
return f;
}
}
答案 0 :(得分:3)
如果您能负担 Java 8
,则可以使用Method Referencespackage javaapplication4;
import java.util.function.Function;
public class JavaApplication4 {
public static class Pruebas
{
public static double fun1(double x)
{
return x*1;
}
public static double fun2(double x){
return x*2;
}
public static double fun3(double x){
return x*3;
}
public static double eval(Function<Double, Double> fun,double x0)
{
double f=fun.apply(x0);
return f;
}
}
public static void main(String[] args)
{
System.out.println(Pruebas.eval(Pruebas::fun3, 5));
}
}
答案 1 :(得分:0)
通常,这样做的方法是创建一个接口,然后有3个实现类。例如,
public interface FuncInterface
{
public double func(double x);
}
public class Pruebas {
public class Func1 implements FuncInterface {
public static double func(double x){
return x*1;
}
}
public class Func2 implements FuncInterface {
public static double func(double x){
return x*2;
}
}
public class Func3 implements FuncInterface {
public static double func(double x){
return x*3;
}
}
public static double eval(FuncInterface funcI,double x0){
/* funx at this point i expect it to be fun1, fun2 or fun3 */
double f=funcI.func(x0);
return f;
}
}