java valueof 枚举,Java枚举valueOf()有多个值?

I have a problem in Java using Enums.

I have read the documentation about assigning value parameters to Enums.

But, my question is what about multiple values, is it possible?

This what I would like to achieve:

I have an Enum for languages. Each language is represented by its name and some shorter aliases (not always, and not always the same number of aliases)

Here is an example:

public enum Language{

English("english", "eng", "en", "en_GB", "en_US"),

German("german", "de", "ge"),

Croatian("croatian", "hr", "cro"),

Russian("russian")

}

Can I just define an Enum like this and get the right enum values by calling Language.valueOf() ???

解决方案

This is probably similar to what you're trying to achieve.

public enum Language{

English("english", "eng", "en", "en_GB", "en_US"),

German("german", "de", "ge"),

Croatian("croatian", "hr", "cro"),

Russian("russian");

private final List values;

Language(String ...values) {

this.values = Arrays.asList(values);

}

public List getValues() {

return values;

}

}

Remember enums are a class like the others; English("english", "eng", "en", "en_GB", "en_US") is calling the enum constructor.

You could then retrieve the enum value corresponding to a string through a search method (you can put it as a static method in the enum again).

public static Language find(String name) {

for (Language lang : Language.values()) {

if (lang.getValues().contains(name)) {

return lang;

}

}

return null;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值