【问题标题】:How to call a static method from a class given that you only have the class's string name (and the method name / parameters) - in Java鉴于您只有类的字符串名称(和方法名称/参数),如何从类中调用静态方法 - 在 Java 中
【发布时间】:2016-06-18 10:30:21
【问题描述】:

我想创建一个可以被各种不同的类调用的静态方法。所有将调用此方法的类都有一个名为“evaluate”的方法,我想从该方法中调用它。

所有涉及的类和方法都是静态的。然而,“评估”方法在每个拥有它的类中实现方式不同。如何从每次调用该方法的特定类调用评估方法?

谢谢!!

这是伪代码/更多信息

我的项目的目标是对任意数量的 sig-figs 实现牛顿和二分法近似方法

特别是关于二分法 - 它应该能够与任何可评估的函数一起使用

这不是一个理想的方法,但是由于我的作业(高中老师)的框架,我的每个不同的功能都嵌入了一个

静态类,作为称为“评估”的单个方法。

二分法依赖于能够一遍又一遍地调用评估方法来找到零。我希望能够调用每个特定类的

从单独的二分法评估。

评估类示例:

//evaluate the function x^2+5x+3
public class Problem1{
 public void main(String[] args){
   //code here

   //call bisectionMethod() here

  }

  //various other methods

  //the one that i'm concerned about
  public static double evaluate(double input){
    //return output for x^2+5x+3
  }

}  //several classes like this, with different functions


public class Bisection{

  //filler methods


  //this one:
  public static double[] bisectionMethod(){  //don't know if it should have inputs - it has to be able to figure out which eval it's using
    //do the bisection method
    call evaluate(double input) here
  }
}

【问题讨论】:

  • 所有类都实现了一个通用接口吗?
  • @bradimus 我认为这是他问题的重点;我认为他还没有学过接口,接口是这个问题的一种可能答案(如果我错了,请纠正我)
  • @mjones.udri 我知道接口,这是一个稍微不同的问题
  • 一般来说,我会说您正在尝试针对系统工作,并建议将所有其他静态类和方法转换为非静态版本。你的用例是什么?
  • 嗨,Alex - 请参阅原始评论。我试图让我的问题更具体。我的一个主要问题是这是为了学校作业,所以对我能做什么和不能做什么有一些稍微奇怪/任意的限制

标签: java oop methods


【解决方案1】:

这是您不能将静态方法放入接口的限制。解决方法是使用 Java 反射 API:

public Object callStaticEvaluate(Class<?> clazz, double input) throws Exception {
    return clazz.getMethod("evaluate", double.class).invoke(null, input);
}

What is reflection and why is it useful?

【讨论】:

    【解决方案2】:

    你不能通过任何干净的方式来做到这一点。OOP 不支持任何这样的结构。你必须使用反射。 Invoking a static method using reflection

    原来如此——

    public static <T extends XXX> void evaluate(Class<T> c){
            // invoke static method on c using reflection
        }
    

    【讨论】:

    • 不正确;超类是实现 OP 想要的一种干净的方式。
    • @mjones.udri 不正确;静态方法不能添加到接口中,也不能在子类中虚拟化(因为没有您调用方法的实例)。
    【解决方案3】:

    鉴于 Java 8 语法,除了使用接口和反射之外,还有第三种方法:

    Bisection

    import java.util.function.DoubleUnaryOperator;
    
    public class Bisection {
    
      public static double[] bisectionMethod(DoubleUnaryOperator evalFn, <other args>)
        // invoke the function
        double in  = ...;
        double out = fn.applyAsDouble(in);
        ...
      }
    }   
    

    并使用静态评估函数的方法句柄调用Bisection

    Bisection.bisectionMethod(Problem1::evaluate)
    

    【讨论】:

    • JDK中已经存在这样的接口:DoubleUnaryOperator (docs.oracle.com/javase/8/docs/api/java/util/function/…)
    • 另外,上面的代码还有几个问题,包括方法声明,未定义的局部变量,和声明不匹配的方法调用。
    • @SashaSalauyou 很棒 - 看过但没有找到这个界面 - 将其合并到我的答案中
    猜你喜欢
    • 2015-04-08
    • 1970-01-01
    • 2012-07-09
    • 2011-08-26
    • 2017-10-10
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多