我正在使用標記介面來實作偽列舉繼承。
假設我將 Marker 類定義如下:
public interface FieldInterface
現在我有 5 個實作這個介面的列舉類。
enum Field1 implements FieldInterface
enum Field2 implements FieldInterface
enum Field3 implements FieldInterface
enum Field4 implements FieldInterface
enum Field5 implements FieldInterface
上面的 5 個列舉“欄位”類中的每一個都定義了與該欄位型別相關的列舉串列。例如, enumField1可能會定義 enums: Field1A, Field1B, Field1C。列舉Field2可能會定義列舉:Field2A, Field2B, Field2C
現在我需要將每個列舉的純文本表示形式轉換為相應的列舉(類似于呼叫enum.valueOf(String)),而不知道字串屬于 5 個列舉類中的哪一個。
實作此目的的一種方法可能是reflection首先檢索實作所述介面的所有類的串列,然后遍歷所有 5 個列舉類,直到找到匹配項。但是,如果可能,我更愿意避免反射(主要是由于性能原因)。
還有什么其他選擇可以解決這個問題?
謝謝
uj5u.com熱心網友回復:
Map<String, Enum<?>> 的傳統實作,處理幾個列舉類有一點復雜性。靜態最終映射實體在介面中定義并在所有列舉之間共享。
class Main {
// Nice shorthand for an anonymous instance of X
private static final X X = new X(){};
public static void main(final String[] args) {
// Enum classes must be loaded
loadEnums();
// You can call get() on any enum constant but that would look unintiitve. We need an instance of X
System.out.println(X.get("FIELD1B"));
}
private static void loadEnums() {
IntStream.range(1, 10).mapToObj(n -> Main.class.getPackageName() ".Main$Field" n).forEach(Main::loadEnum);
}
private static void loadEnum(String name) {
try {
Class.forName(name);
} catch (ClassNotFoundException e) {}
}
/**
* All enums implement this marker interface and therefore share access to a static map from the name of the enum to its value.
*/
interface X {
Map<String, X> map = new HashMap<>();
/**
* This shared method uses enum's name method to get enum's string representation.
*/
default void add() {
map.put(name(), this);
}
default X get(String key) {
return map.get(key);
}
/**
* This method is always overwritten by each enum because all enums have a name() method. It is declared here so that we can provide add() method without requiring name passed as an argument. having a default implementation allows us to new X(){}.
*/
default String name() {
return null;
}
}
enum Field1 implements X {
FIELD1A, FIELD1B, FIELD1C;
// We have to call add() to place each enum value in the shared map
Field1() { add(); }
}
enum Field2 implements X {
FIELD2A, FIELD2B, FIELD2C;
Field2() { add(); }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/464910.html
上一篇:Matlab到Python的轉換:SyntaxError:無法分配給函式呼叫
下一篇:從母類物件列印擴展類物件的值
