接口:
public interface IPersistentEnum<T> {
T getKey();
String getValue();
}
工具类:
public final class PersistentEnum {
/**
*
* @param <T>
* @param <V>
* @param clazz
* @param value
* @return
*/
public static <T extends Enum<T> & IPersistentEnum<V>, V> T parse(Class<T> clazz, V key) {
for (T t : clazz.getEnumConstants()) {
if (isEquals(t.getKey(), key)) {
return t;
}
}
return null;
}
private static <T> boolean isEquals(T lhs, T rhs) {
if (lhs == null && rhs == null) {
return true;
} else if (lhs == null || rhs == null) {
return false;
} else {
return lhs.equals(rhs);
}
}
}
Enum example:
public enum ESex implements IPersistentEnum<Integer> {
MEN(1,"男"),WOMAN(0,"女");
private int key;
private String value = null;
private ESex(Integer key, String value) {
this.key = key;
this.value = value;
}
@Override
public String getValue() {
return value;
}
@Override
public Integer getKey() {
return key;
}
public static ESex parse(int key) {
return PersistentEnum.parse(ESex.class, key);
}
}
Test:
public class ESexTest {
/**
* @param args
*/
public static void main(String[] args) {
String sex1 = PersistentEnum.parse(ESex.class, 1).getValue();
System.out.println(sex1);
//如果枚举里写了parse静态方法可以直接使用
String sex2 = ESex.parse(1).getValue();
System.out.println(sex2);
}
}
输出结果:
男
男