java
的ENUM
是我們常用的東西。ENUM
也可以是TEST_ONE(10001)
這種形式罩引。
必要的時(shí)候就可以通過(guò)ENUM
的name
去獲得屬性胳螟。
有時(shí)候可能有這種需求胁住,想從屬性去獲得ENUM
的name
。這種的話需要?jiǎng)?chuàng)建一個(gè)靜態(tài)方法將ENUM
的數(shù)據(jù)以哈希值的方式存入痘儡,其中將屬性作為key
辕万。
public enum TestType
{
//樣例
TEST_ONE(10001),
TEST_TWO(10002);
private int code;
//設(shè)置ENUM的格式
TestType(int code){ this.code = code; }
public int getCode(){ return this.code; }
@Override
public String toString(){ return this.name(); }
//創(chuàng)建MAP對(duì)象
private static final Map<Integer,TestType> map = new HashMap<>();
static
{
//賦值
for (TestType t: EnumSet.allOf(TestType.class))
{
map.put(t.getCode(),t);
}
}
//提供方法調(diào)用
public static TestType getType(int code)
{
return map.get(code);
}
}
需要反向獲取的時(shí)候直接調(diào)用getType
方法就行