方便地在enum和int / String之间映射 [英] Conveniently map between enum and int / String
问题描述
当使用只能获取有限数量的值的变量/参数时,我尝试始终使用Java的 enum
,如
When working with variables/parameters that can only take a finite number of values, I try to always use Java's enum
, as in
public enum BonusType {
MONTHLY, YEARLY, ONE_OFF
}
只要我留在我的代码中,那就行了。但是,我经常需要与其他使用纯文本 int
(或 String
)的代码接口,或者我需要从数据库读取/写入数据,数据存储为数字或字符串。
As long as I stay inside my code, that works fine. However, I often need to interface with other code that uses plain int
(or String
) values for the same purpose, or I need to read/write from/to a database where the data is stored as a number or string.
在这种情况下,我想要一个方便的方法来将每个枚举值与一个整数相关联,这样我可以转换这两种方式(换句话说,我需要一个可逆枚举)。
In that case, I'd like to have a convenient way to associate each enum value with a an integer, such that I can convert both ways (in other words, I need a "reversible enum").
to int is easy:
Going from enum to int is easy:
public enum BonusType {
public final int id;
BonusType(int id) {
this.id = id;
}
MONTHLY(1), YEARLY(2), ONE_OFF(3);
}
然后我可以访问int值 BonusType x = MONTHLY;然而,我可以看到没有一个好的方法,反向,即从int到枚举。。int id = x.id;
。
Then I can access the int value as BonusType x = MONTHLY; int id = x.id;
.
理想情况下,像
BonusType bt = BonusType.getById(2);
我可以想出的唯一解决方案是:
The only solutions I could come up with are:
- 在枚举中加入一个查找方法,使用
BonusType.values()
填充一个地图int - > enum然后缓存并使用它进行查找。会工作,但是我必须将这个方法同样复制到我使用的每个枚举: - (。 - 将lookup方法放入一个静态实用程序类中,然后我只需要一个lookup方法,但是我不得不使用反射来让它为任意枚举工作。
- Put a lookup method into the enum, which uses
BonusType.values()
to fill a map "int -> enum", then caches that and uses it for lookups. Would work, but I'd have to copy this method identically into each enum I use :-(. - Put the lookup method into a static utility class. Then I'd only need one "lookup" method, but I'd have to fiddle with reflection to get it to work for an arbitrary enum.
任何其他想法/见解?
推荐答案
http://www.javaspecialists.co.za/archive/Issue113.html
解决方案开始时类似于你的int值作为枚举定义的一部分,然后继续创建一个基于泛型的查找实用程序:
The solution starts out similar to yours with an int value as part of the enum definition. He then goes on to create a generics-based lookup utility:
public class ReverseEnumMap<V extends Enum<V> & EnumConverter> {
private Map<Byte, V> map = new HashMap<Byte, V>();
public ReverseEnumMap(Class<V> valueType) {
for (V v : valueType.getEnumConstants()) {
map.put(v.convert(), v);
}
}
public V get(byte num) {
return map.get(num);
}
}
这个解决方案很好, with reflection',因为它是基于所有枚举类型隐式继承Enum接口的事实。
This solution is nice and doesn't require 'fiddling with reflection' because it's based on the fact that all enum types implicitly inherit the Enum interface.
这篇关于方便地在enum和int / String之间映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!