java - 假设您只有类的字符串名称(以及方法名称/参数),如何从类调用静态方法 - 在 Java 中

标签 java oop methods

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

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

谢谢!!

这是伪代码/更多信息

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

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

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

静态类,作为一个名为“evaluate”的单一方法。

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

通过单独二分法进行评估。

评估类示例:

//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
  }
}

最佳答案

这是一个限制,不能将静态方法放入接口(interface)中。解决方法是使用 Java Reflection 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?

关于java - 假设您只有类的字符串名称(以及方法名称/参数),如何从类调用静态方法 - 在 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800277/

相关文章:

java - Selenium 脚本未运行

java - Runnable 的时间确定性执行

c++ - C++中的动态调度和后期绑定(bind)有什么区别?

oop - 在 MATLAB 中根据名称实例化类

java - Jersey:可以从 ResourceInfo 获取 getResourceClass() 实现的接口(interface)吗?

Java notSerializedException错误

php - 像谷歌一样的分页背后的逻辑

perl 将对象方法引用作为参数传递给函数

java - 非静态变量的引用

c++ - 接受整数或字符串的方法。 C++