invoke是反射中调用类的方法的实现:如下所示
getValueMethod.invoke(obj)实际上是:getValueMethod.getValue()
/**
*
* <p>
* Description: 转换
* </p>
*
* @param em em
* @param param param
* @param isToName 是否是将value转换为name
* @return 转换后的值
*/
private static Object change(Enum em, Object param, boolean isToName) {
if (param == null) {
return null;
}
Class clazz = em.getDeclaringClass();
try {
Method getNameMethod = clazz.getMethod("getName");
Method getValueMethod = clazz.getMethod("getValue");
Object[] constants = clazz.getEnumConstants();
Object result = null;
for (Object obj : constants) {
if (isToName) {
int value = (Integer) getValueMethod.invoke(obj);
if (value == (Integer) param) {
result = getNameMethod.invoke(obj);
break;
}
} else {
String name = (String) getNameMethod.invoke(obj);
if (name.equals(param)) {
result = getValueMethod.invoke(obj);
break;
}
}
}
return result;
} catch (Exception e) {
logger.error(e.toString(), e);
}
return null;
}