2015-12-04 84 views
1

我有一對夫婦,我想提供一個網上API像處理幾個枚舉類型在一個通用的方式

/get/enum-values?type=<enum-Name> 

枚舉枚舉如下:

public enum Color {RED, GREEN, BLUE}; 
public enum Status {OPEN, DONE, CLOSED}; 
public enum Type {CAR, BIKE, ON_FOOT}; 

而且我想寫的一般處理所有這些枚舉的網絡API中的代碼如下:

Class<?>[] enumsArray = new Class<?>[] { 
    Color.class, Status.class, Type.class 
}; 
List<String> getValuesForEnum(String enumName) { 
    List<String> returnValue = new ArrayList<>(); 
    // Loop over the above array to find enum corresponding to the argument 
    for (Object e: foundEnum.values()) { 
     returnValue.add(e.toString()); 
    } 
    return returnValue; 
} 

上述功能d因爲我不能一般地對待枚舉,所以不能編譯。 有什麼辦法可以使這項工作?

我不希望獨立處理每個枚舉。

也許我可以從一些常見枚舉擴展所有的枚舉?

+0

你能提供一個樣本輸入和預期的輸出? –

+0

getValuesForEnum()的示例輸入可以是「Color」,期望的輸出是{「RED」,「GREEN」,「BLUE」}的數組列表} – user2250246

+0

在這種情況下,您可能想要使用'Map >>'(或者'Map >'而不是僅僅'List' –

回答

2

因爲有泛型的數組問題(編譯錯誤:「不能創建一個通用的陣列」),這是更好地使用Arrays.asList()

private static final List<Class<? extends Enum<?>>> ENUMS = Arrays.asList(
     Color.class, Status.class, Type.class 
); 
private static List<String> getValuesForEnum(String enumName) { 
    for (Class<? extends Enum<?>> enumClass : ENUMS) 
     if (enumClass.getSimpleName().equals(enumName)) { 
      List<String> values = new ArrayList<>(); 
      for (Enum<?> enumConstant : enumClass.getEnumConstants()) 
       values.add(enumConstant.name()); // or enumConstant.toString() 
      return values; 
     } 
    throw new IllegalArgumentException("Unknown enum: " + enumName); 
} 
相關問題