我想将特定的枚举类传递给方法。这可能吗?该方法将接受任何枚举。我正在尝试创建一个函数,该函数将采用一种枚举类型并从中创建一个菜单,返回所选的枚举。
枚举类示例
public enum METHODOFTRANSPORTATION {
CAR("car"), BUS("bus"), COMMUTTER_RAIL("commuter rail"),MAINMENU("GO TO MAIN MENU");
private String choice;
METHODOFTRANSPORTATION(String choice){
this.choice = choice;
}
public String getMethodOfTransportation(){
return choice;
}
}
我的示例类实现了枚举
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Ticket{
private static HashMap<Integer, Ticket> hm= new HashMap<>();
private int ticketID = 0;
private METHODOFTRANSPORTATION methodOfTransportation;
Ticket(){
//Call method of Transportation to create ticket
//GETTING ERROR HERE!
this.methodOfTransportation = createMethodOfTransportation(METHODOFTRANSPORTATION);
}
Ticket(METHODOFTRANSPORTATION methodOfTransportation){
this.methodOfTransportation = methodOfTransportation;
}
public Enum<?> getMethodOfTransportation() {
return methodOfTransportation;
}
public Enum<?> createMenuChoice(Enum<?> e) {
System.out.println("**************************");
Scanner s = new Scanner(System.in);
int input = 0;
boolean intFlag = false;
Enum<?> mot;
//Validate user input for menu selection
do{
//Print our Enums allowed variables
for(int i=0; i< e.getDeclaringClass().getEnumConstants().length; i++){
System.out.printf("%d. %s",i,e.getDeclaringClass().getEnumConstants()[i]);
}
System.out.println("Please enter a valid menu entry (");
for(int i = 0; i< e.getDeclaringClass().getEnumConstants().length; i++){
if(i == e.getDeclaringClass().getEnumConstants().length){
System.out.println(i);
}
else{
System.out.print(i + ",");
}
}
System.out.print("> ");
if(s.hasNextInt()){
input = s.nextInt();
for(int i = 0; i< e.getDeclaringClass().getEnumConstants().length; i++){
if(input == i){
//*********************************************
//HOW DO I RETURN THE CORRESPONDING VALUE HERE?
//*******************************************
mot = ;
}
}
}
else{
s.next();
}
}
while(false);
//WHAT SHOULD I RETURN HERE??
return METHODOFTRANSPORTATION.CAR;
}
}
这可能吗?我只想要一种可以接受任何枚举类并返回枚举值的方法。有更好的方法吗?
基本上我的驱动程序类看起来像
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ticket t = new Ticket();
Enum<?> mot = t.getMethodOfTransportation();
if(mot == METHODOFTRANSPORTATION.CAR){
//....
}
//...
//OR
/*
* switch(mot){
* case(METHODOFTRANSPORTATION.CAR): ...
* ...
* ...
* }
*/
}
}
最佳答案
在 Java 中引用类的正确方法是 ClassName.class
。所以你的行将是:
this.methodOfTransportation = createMethodOfTransportation(METHODOFTRANSPORTATION.class);
METHODOFTRANSPORTATION.class
返回一个 Class
类型对象。然后,您可以使用反射来检查其名称、可能的值等。 Here is more info on enum reflection.
名称 createMethodOfTransportation
但并不合适,因为它与特定枚举 METHODOFTRANSPORTATION
没有任何关系。
关于java - 你能将枚举类传递给方法吗(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31498247/