I want to create a static method that can be called by a variety of different classes. All classes that will call this method have a method called "evaluate", which I want to call from within the method.
All classes and methods involved are static. The "evaluate" method, however, is implemented differently in each class that has it. How do I call the evaluate method from the specific class that called the method each time?
Thanks!!
Here is psudeo code/ more information
The goal of my project is to implement Newton and Bisection approximation methods to an arbitrary number of sig-figs
Concerning the bisection method specifically - it should be able to work with any evaluatable function
This is not an ideal way to do it, but because of the framework of my assignment (high school teacher), each of my different functions are imbedded in a
static class, as a single method called "evaluate".
The bisection method relies on being able to call the evaluate method over and over again to find zeroes. I want to be able to call each specific class's
evaluate from the separate bisection method.
Example of a evaluation class:
//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
}
}
This is a restriction that you cannot put static methods into interface. Workaround is to use Java Reflection API:
public Object callStaticEvaluate(Class<?> clazz, double input) throws Exception {
return clazz.getMethod("evaluate", double.class).invoke(null, input);
}
Given Java 8 syntax there is a third way besides using interfaces and reflection:
In Bisection
write
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);
...
}
}
and invoke Bisection
using a method handle to your static evaluation function:
Bisection.bisectionMethod(Problem1::evaluate)
You cannot do it via any clean way.. OOP does not support any of such structure. You have to use reflection. Invoking a static method using reflection
so it would be -
public static <T extends XXX> void evaluate(Class<T> c){
// invoke static method on c using reflection
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.