天天看點

java 字元串轉枚舉_java 使用反射将字元串轉換為枚舉值,其中枚舉類型可以是以下幾種 - 糯米PHP...

假設我有一個将另一個對象作為id的類:

public SomeClass

{

private final ID id;

...

}

ID然後定義如下。請注意,将枚舉拆分(分為邏輯分組)的原因是,否則單個枚舉将包含1000+個值。這樣就需要接口使所有枚舉仍屬于同一類型。

public interface ID

{

public enum Name1 implements ID { ... constants ... }

public enum Name2 implements ID { ... constants ... }

public enum Name3 implements ID { ... constants ... }

...

}

的對象的SomeClass構造如下:

SomeClass object = new SomeClass(ID.Name2.SOME_VALUE, ... more parameters};

但是,構造SomeClass對象所需的參數存儲在json檔案中,如下所示:

{

"id": "SOME_VALUE",

...

}

What I want to do is to map the string "SOME_VALUE" to ID.Name2.SOME_VALUE. Now, I could do this by having a giant map:

Map conversionMap = HashMap<>();

conversionMap.put("SOME_VALUE", ID.Name2.SOME_VALUE);

conversionMap.put("SOME_OTHER_VALUE", ID.Name3.SOME_OTHER_VALUE);

... etc

but I want to do it automatically using reflection from a static method inside the ID interface (some very rough pseudocode):

public interface ID

{

public static ID getIdFromString(String key)

{

List declaredEnums = ID.class.getDeclaredEnums();

for (Enum declaredEnum : declaredEnums)

{

for (EnumValue value : declaredEnum)

{

if (value.equals(key)

return value;

}

}

}

public enum Name1 implements ID { ... constants ... }

public enum Name2 implements ID { ... constants ... }

public enum Name3 implements ID { ... constants ... }

...

}

How would I do such a thing? I am getting lost in the reflection here, and having searched through many other questions and answers I still seem to not be any closer to the answer.

Note that I could also implement this using 1000+ integer constants and providing a string > integer mapping for that, but using enums feels cleaner. Now that I have hit this snag I am not so convinced of the cleanliness anymore though. It is starting to feel like I am trying to fit a round peg into a square hole.

UPDATE: I ended up using the accepted answer as the solution and modified it a tiny bit to work with my code:

public static ID getIdFromString(String key)

{

Optional> id = Arrays.stream(ID.class.getDeclaredClasses())

.filter(Class::isEnum)

.flatMap(aClass -> Arrays.stream(aClass.getEnumConstants()))

.filter(enumValue -> enumValue.toString().equals(key))

.findFirst();

return (ID)id.get();

}

Beware that this code does not do any checking at all, so you should probably add some checks to it to handle invalid keys, and maybe even handle enums that are declared in ID but do not implement the ID interface.