Disclaimer: I am not going to say that I am the most experienced Java person. There could be easier ways to do what I have in my examples. But this is a question about turning a string entry into an Enum class, not an enum variable. I tried to explain as best as I could.
This is a simple version of what I want to do. I will have two different enums and I want to choose one or the other based off what the user wants. And example of this, in code, would be
public enum Letters {
A, B, C, D, E, ... , X, Y, Z
}
public enum Numbers {
ONE, TWO, THREE, ..., EIGHT, NINE, TEN
}
public static void main(String [] args) {
System.out.println("Enter in you choice, letters (Letters) or numbers(Numbers)");
String entry = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try {
entry = reader.readLine();
}
catch(Exception e){};
...
}
I want to make it so the user, if he enters in "Letters" it will be able to take the string entry and turn it into a variable reference to the Letters Enum. The ellipses are place holders for code. I want to eventually use this so I can use
for (answer n : variable.values()) {
System.out.println(n);
}
instead of
if (answer.equals("Numbers")) {
Numbers n;
for (n : Numbers.values()) {
System.out.println(n);
}
} else {
Letters l;
for (l : Letters.values()) {
System.out.println(l);
}
}
I have tried doing
Class<?> c = Class.forName("Letters");
but it doesn't work.
In my real world example, I have 3 .java files which contains separate classes, and an enum in each of them. There is Sandwich, Beer, and Chip class and their enums are Sandwiches, Beers, Chips. Those classes implement an interface VendingMachineItem. And finally, that interface is part of a vendingMachine package. I don't know if those matter, but that's all the info that I can give.