1
2
3
4
5
6
7
8
9
10
11
12
13
14 package olg.csv.bean;
15
16 import java.beans.BeanInfo;
17 import java.beans.IntrospectionException;
18 import java.beans.Introspector;
19 import java.beans.PropertyDescriptor;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26
27
28
29
30
31
32
33 public final class Util {
34
35
36
37
38 private static final Logger LOGGER = LoggerFactory.getLogger(Util.class);
39
40
41
42
43 private Util() {
44
45 }
46
47
48
49
50
51
52
53
54
55
56
57
58
59 public static <T> Class<?> identifySetType(Class<T> clazz, String field) throws NoSuchMethodException {
60
61 Method setter = identifySetter(clazz, field);
62
63 if (setter == null) {
64 throw new NoSuchMethodException(field + " has no setter");
65 }
66 return setter.getParameterTypes()[0];
67
68 }
69
70
71
72
73
74
75
76
77
78
79
80
81 public static <T> Method identifySetter(Class<T> clazz, String field) {
82 Method method = null;
83 if (clazz != null && field != null) {
84 try {
85 BeanInfo info = Introspector.getBeanInfo(clazz);
86 for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
87 if (field.equals(pd.getName())) {
88 method = pd.getWriteMethod();
89 break;
90 }
91 }
92 } catch (IntrospectionException e) {
93 LOGGER.error(String.format("%s.%s setter search : ", clazz.getSimpleName(), field), e);
94 }
95 }
96 return method;
97
98 }
99
100
101
102
103
104
105
106
107
108
109
110
111
112 public static <T> Method identifyGetter(Class<T> clazz, String field) {
113 Method method = null;
114 if (clazz != null && field != null) {
115 try {
116 BeanInfo info = Introspector.getBeanInfo(clazz);
117 for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
118 if (field.equals(pd.getName())) {
119 method = pd.getReadMethod();
120 break;
121 }
122 }
123 } catch (IntrospectionException e) {
124 LOGGER.error(String.format("%s.%s getter search : ", clazz.getSimpleName(), field), e);
125 }
126 }
127 return method;
128
129 }
130
131
132
133
134
135
136
137
138 public static String emptyToNull(String str) {
139 String retour = null;
140 if (!"".equals(str)) {
141 retour = str;
142 }
143 return retour;
144 }
145
146
147
148
149
150
151
152
153
154
155 public static boolean asSubClass(Class<?> clazzA, Class<?> clazzB) {
156 try {
157 clazzB.asSubclass(clazzA);
158 return true;
159 } catch (ClassCastException ex) {
160
161 }
162 return false;
163 }
164
165
166
167
168
169
170
171
172
173
174 public static <T> boolean isConcrete(Class<T> clazz) {
175 return clazz.isPrimitive() || clazz.isEnum()
176 || (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()));
177 }
178
179 }