Is is possible in Java to call a method based on a field value? For example, I ask the user what soda they want. They enter their selection and the value of the field that holds their selection is used to call the method.
Obviously the below code doesn’t work. But I’m hoping it will illustrate my intent. Is this sort of thing even possible in Java?
The goal is to effectively switch without using IF or SWITCH statements.
import java.util.Scanner;
public class FieldResolutionTest
{
public static void main (String[] args)
{
Scanner inputScanner = new Scanner(System.in);
MethodTester test = new MethodTester();
System.out.println("Please enter ONE or TWO");
String selection = inputScanner.nextLine();
test.(selection)();
}
}
public class MethodTester
{
public void ONE()
{
System.out.println("You ran method ONE");
}
public void TWO()
{
System.out.println("You ran method TWO");
}
}
You can use reflection. This is your example with minimal modifications:
Of course, you need to add some error handling. For example, you should check that the user entered the name of one of the allowed methods, like this: