[英]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
我想创建一个可以由各种不同的类调用的静态方法。 所有将调用此方法的类都具有一个称为“求值”的方法,我想从该方法中调用该方法。
涉及的所有类和方法都是静态的。 但是,“评估”方法在具有该方法的每个类中的实现方式有所不同。 如何从每次调用方法的特定类中调用评估方法?
谢谢!!
这是伪代码/更多信息
我项目的目标是对任意数量的sig-figs实施Newton和Bisection逼近方法
关于二等分法-它应该能够使用任何可评估的函数
这不是理想的方法,但是由于我的任务框架(高中老师),我每个不同的职能都嵌入了
静态类,称为“评估”的单个方法。
二等分方法依赖于能够一次又一次调用评估方法以找到零。 我希望能够呼叫每个特定班级的
从单独的二等分法进行评估。
评估类示例:
//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
}
}
这是不能将静态方法放入接口的限制。 解决方法是使用Java Reflection API:
public Object callStaticEvaluate(Class<?> clazz, double input) throws Exception {
return clazz.getMethod("evaluate", double.class).invoke(null, input);
}
给定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)
您不能通过任何干净的方法来执行此操作。OOP不支持任何此类结构。 您必须使用反射。 使用反射调用静态方法
所以它将是-
public static <T extends XXX> void evaluate(Class<T> c){
// invoke static method on c using reflection
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.