1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.exception.ExceptionHelper;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* 字符串和枚举进行转换
* @author 颜佐光
*/
public class EnumHelper {
private static HashMap<Class, Method> CacheMethod = new HashMap<>();
public static <T extends Enum<T>> T toEnum(String vStr, T vDefault) {
Class<T> vType = (Class<T>) vDefault.getClass();
T result = vDefault;
try {
if (!StringHelper.isEmpty(vStr)) {
result = Enum.valueOf(vType, vStr);
}
} catch (Exception ex) {
ExceptionHelper.handleException(EnumHelper.class, ex, vStr);
}
return result;
}
public static <T> T toEnum(Class<T> vType, String vStr) {
return toEnum(vType, vStr, null);
}
public static <T> T toEnum(Class<T> vType, String vStr, T vDefault) {
T result = vDefault;
try {
if (StringHelper.isInteger(vStr)) {
result = toEnum(vType, StringHelper.toInt(vStr));
} else if (!StringHelper.isEmpty(vStr)) {
result = (T) Enum.valueOf((Class) vType, vStr);
}
} catch (Exception ex) {
ExceptionHelper.handleException(EnumHelper.class, ex, vStr);
}
if (result == null && vDefault == null) {
result = toEnum(vType, 0);
}
return result;
}
public static <T> T toEnum(Class<T> vType, int i) {
T result = null;
try {
if (CacheMethod.containsKey(vType)) {
Method met = CacheMethod.get(vType);
result = (T) met.invoke(null, i);
} else {
Method[] vMets = vType.getMethods();
for (Method vMet : vMets) {
String vName = vMet.getName();
if ("forValue".equals(vName)
&& vMet.getParameterTypes().length == 1) {
// Class vTempType = vMet.getParameterTypes()[0];
Object obj = vMet.invoke(null, i);
result = (T) obj;
CacheMethod.put(vType, vMet);
break;
}
}
}
} catch (Exception ex) {
ExceptionHelper.handleException(EnumHelper.class, ex, i);
}
return result;
}
}