通过Key获取枚举对象,方法不太公用,可以根据项目实际情况改造下
public class EnumsUtil {
public static<T> String getValue(final Class<T> c, Object code){
String value = null;
if(code==null){
return value;
}
T t = getEnum(c,code);
if(t==null){
return value;
}
try {
Method getValue = t.getClass().getMethod("getValue", null);
if(getValue!=null){
Object invoke = getValue.invoke(t);
return String.valueOf(invoke);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return value;
}
public static<T> T getEnum(final Class<T> c, Object code){
T value = null;
if(code==null){
return null;
}
try {
ArrayList<T> ts = new ArrayList<T>(Arrays.asList(c.getEnumConstants()));
Object invoke = null;
for (T t : ts) {
Method getCode = t.getClass().getMethod("getCode", null);
if(getCode==null){
return null;
}
invoke = getCode.invoke(t);
if(invoke.equals(code)){
return t;
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return value;
}
public static void main(String[] args) {
String str = getValue(StatusCodeEnums.class, 1);
System.out.println(str);
StatusCodeEnums value = getEnum(StatusCodeEnums.class, 1);
System.out.println(value.getValue());
}
@Getter
public enum StatusCodeEnums {
enable(1,"有效")
,disable(0,"有效");
private Integer code;
private String value;
StatusCodeEnums(Integer code, String value) {
this.code = code;
this.value = value;
}
}