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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值