java
的ENUM
是我们常用的东西。ENUM
也可以是TEST_ONE(10001)
这种形式。
必要的时候就可以通过ENUM
的name
去获得属性。
有时候可能有这种需求,想从属性去获得ENUM
的name
。这种的话需要创建一个静态方法将ENUM
的数据以哈希值的方式存入,其中将属性作为key
。
public enum TestType
{
//样例
TEST_ONE(10001),
TEST_TWO(10002);
private int code;
//设置ENUM的格式
TestType(int code){ this.code = code; }
public int getCode(){ return this.code; }
@Override
public String toString(){ return this.name(); }
//创建MAP对象
private static final Map<Integer,TestType> map = new HashMap<>();
static
{
//赋值
for (TestType t: EnumSet.allOf(TestType.class))
{
map.put(t.getCode(),t);
}
}
//提供方法调用
public static TestType getType(int code)
{
return map.get(code);
}
}
需要反向获取的时候直接调用getType
方法就行