【问题标题】:Java calling methods from other methodsJava 从其他方法调用方法
【发布时间】:2016-03-14 16:16:04
【问题描述】:

有没有办法可以将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;
    }
}

【问题讨论】:

  • 有几种方法。使用哪个取决于具体情况。你想达到什么目的?
  • 根据您想要做什么,Strategy and Template Method design patterns 可能对此有用。
  • 您好,感谢您的回复,我简化了问题,但我正在做的是一个热力学程序,它使用了很多数学,特别是数值方法,需要我多次评估很多函数每次使用不同的输入参数。
  • 您在使用 Java 8 吗?还是更早的版本?

标签: java methods


【解决方案1】:

如果你负担得起Java 8

,你可以使用Method References
package 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));
    }

}

【讨论】:

    【解决方案2】:

    通常,这样做的方法是创建一个接口,然后有 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多