Is it possible to pass a method as a parameter in Java? If I can't what would be the best course of action for the method below without having to repeat code.
public void enterUserInput(javax.swing.JTextField inputField, javax.swing.JTextField outputField, method rangeChecking){
String input;
double output;
input = inputField.getText();
output = Double.parseDouble(input);
if(rangeChecking(output)){
outputField.setText(input);
inputField.setText(null);
}
I will be calling a rangeChecking method from a different class and each time I call the enterUserInput the rangeChecking method will be different
解决方案
You should use an interface to do it.
You pass the interface that declares the desired function to the method, and invoke the desired method. The specific method that will be invoked is the one implemented by the implementing class.
code sample:
public static interface Foo { //this is the interface declaration
public void print();
}
public static class Bar implements Foo { //Bar is an implementing class
public void print() {
System.out.println("Bar");
}
}
public static void test(Foo foo) { //the method accepts an interface
foo.print(); //and invokes it, the implementing class' print() will be invoked.
}
public static void main(String... args) throws Exception {
test(new Bar()); //invoke test() with the class implementing the interface
}