1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.reflection;
17
18 import java.lang.invoke.MethodHandle;
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.lang.reflect.Array;
22 import java.lang.reflect.Constructor;
23 import java.lang.reflect.Field;
24 import java.lang.reflect.GenericArrayType;
25 import java.lang.reflect.Method;
26 import java.lang.reflect.Modifier;
27 import java.lang.reflect.ParameterizedType;
28 import java.lang.reflect.ReflectPermission;
29 import java.lang.reflect.Type;
30 import java.text.MessageFormat;
31 import java.util.AbstractMap;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Locale;
38 import java.util.Map;
39 import java.util.Map.Entry;
40
41 import org.apache.ibatis.reflection.invoker.AmbiguousMethodInvoker;
42 import org.apache.ibatis.reflection.invoker.GetFieldInvoker;
43 import org.apache.ibatis.reflection.invoker.Invoker;
44 import org.apache.ibatis.reflection.invoker.MethodInvoker;
45 import org.apache.ibatis.reflection.invoker.SetFieldInvoker;
46 import org.apache.ibatis.reflection.property.PropertyNamer;
47
48
49
50
51
52
53
54 public class Reflector {
55
56 private static final MethodHandle isRecordMethodHandle = getIsRecordMethodHandle();
57 private final Type type;
58 private final Class<?> clazz;
59 private final String[] readablePropertyNames;
60 private final String[] writablePropertyNames;
61 private final Map<String, Invoker> setMethods = new HashMap<>();
62 private final Map<String, Invoker> getMethods = new HashMap<>();
63 private final Map<String, Entry<Type, Class<?>>> setTypes = new HashMap<>();
64 private final Map<String, Entry<Type, Class<?>>> getTypes = new HashMap<>();
65 private Constructor<?> defaultConstructor;
66
67 private final Map<String, String> caseInsensitivePropertyMap = new HashMap<>();
68
69 private static final Entry<Type, Class<?>> nullEntry = new AbstractMap.SimpleImmutableEntry<>(null, null);
70
71 public Reflector(Type type) {
72 this.type = type;
73 if (type instanceof ParameterizedType) {
74 this.clazz = (Class<?>) ((ParameterizedType) type).getRawType();
75 } else {
76 this.clazz = (Class<?>) type;
77 }
78 addDefaultConstructor(clazz);
79 Method[] classMethods = getClassMethods(clazz);
80 if (isRecord(clazz)) {
81 addRecordGetMethods(classMethods);
82 } else {
83 addGetMethods(classMethods);
84 addSetMethods(classMethods);
85 addFields(clazz);
86 }
87 readablePropertyNames = getMethods.keySet().toArray(new String[0]);
88 writablePropertyNames = setMethods.keySet().toArray(new String[0]);
89 for (String propName : readablePropertyNames) {
90 caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
91 }
92 for (String propName : writablePropertyNames) {
93 caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
94 }
95 }
96
97 private void addRecordGetMethods(Method[] methods) {
98 Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0)
99 .forEach(m -> addGetMethod(m.getName(), m, false));
100 }
101
102 private void addDefaultConstructor(Class<?> clazz) {
103 Constructor<?>[] constructors = clazz.getDeclaredConstructors();
104 Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0).findAny()
105 .ifPresent(constructor -> this.defaultConstructor = constructor);
106 }
107
108 private void addGetMethods(Method[] methods) {
109 Map<String, List<Method>> conflictingGetters = new HashMap<>();
110 Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
111 .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
112 resolveGetterConflicts(conflictingGetters);
113 }
114
115 private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
116 for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
117 Method winner = null;
118 String propName = entry.getKey();
119 boolean isAmbiguous = false;
120 for (Method candidate : entry.getValue()) {
121 if (winner == null) {
122 winner = candidate;
123 continue;
124 }
125 Class<?> winnerType = winner.getReturnType();
126 Class<?> candidateType = candidate.getReturnType();
127 if (candidateType.equals(winnerType)) {
128 if (!boolean.class.equals(candidateType)) {
129 isAmbiguous = true;
130 break;
131 }
132 if (candidate.getName().startsWith("is")) {
133 winner = candidate;
134 }
135 } else if (candidateType.isAssignableFrom(winnerType)) {
136
137 } else if (winnerType.isAssignableFrom(candidateType)) {
138 winner = candidate;
139 } else {
140 isAmbiguous = true;
141 break;
142 }
143 }
144 addGetMethod(propName, winner, isAmbiguous);
145 }
146 }
147
148 private void addGetMethod(String name, Method method, boolean isAmbiguous) {
149 MethodInvoker invoker = isAmbiguous ? new AmbiguousMethodInvoker(method, MessageFormat.format(
150 "Illegal overloaded getter method with ambiguous type for property ''{0}'' in class ''{1}''. This breaks the JavaBeans specification and can cause unpredictable results.",
151 name, method.getDeclaringClass().getName())) : new MethodInvoker(method);
152 getMethods.put(name, invoker);
153 Type returnType = TypeParameterResolver.resolveReturnType(method, type);
154 getTypes.put(name, Map.entry(returnType, typeToClass(returnType)));
155 }
156
157 private void addSetMethods(Method[] methods) {
158 Map<String, List<Method>> conflictingSetters = new HashMap<>();
159 Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 1 && PropertyNamer.isSetter(m.getName()))
160 .forEach(m -> addMethodConflict(conflictingSetters, PropertyNamer.methodToProperty(m.getName()), m));
161 resolveSetterConflicts(conflictingSetters);
162 }
163
164 private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
165 if (isValidPropertyName(name)) {
166 List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
167 list.add(method);
168 }
169 }
170
171 private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
172 for (Entry<String, List<Method>> entry : conflictingSetters.entrySet()) {
173 String propName = entry.getKey();
174 List<Method> setters = entry.getValue();
175 Class<?> getterType = getTypes.getOrDefault(propName, nullEntry).getValue();
176 boolean isGetterAmbiguous = getMethods.get(propName) instanceof AmbiguousMethodInvoker;
177 boolean isSetterAmbiguous = false;
178 Method match = null;
179 for (Method setter : setters) {
180 if (!isGetterAmbiguous && setter.getParameterTypes()[0].equals(getterType)) {
181
182 match = setter;
183 break;
184 }
185 if (!isSetterAmbiguous) {
186 match = pickBetterSetter(match, setter, propName);
187 isSetterAmbiguous = match == null;
188 }
189 }
190 if (match != null) {
191 addSetMethod(propName, match);
192 }
193 }
194 }
195
196 private Method pickBetterSetter(Method setter1, Method setter2, String property) {
197 if (setter1 == null) {
198 return setter2;
199 }
200 Class<?> paramType1 = setter1.getParameterTypes()[0];
201 Class<?> paramType2 = setter2.getParameterTypes()[0];
202 if (paramType1.isAssignableFrom(paramType2)) {
203 return setter2;
204 }
205 if (paramType2.isAssignableFrom(paramType1)) {
206 return setter1;
207 }
208 MethodInvoker invoker = new AmbiguousMethodInvoker(setter1,
209 MessageFormat.format(
210 "Ambiguous setters defined for property ''{0}'' in class ''{1}'' with types ''{2}'' and ''{3}''.", property,
211 setter2.getDeclaringClass().getName(), paramType1.getName(), paramType2.getName()));
212 setMethods.put(property, invoker);
213 Type[] paramTypes = TypeParameterResolver.resolveParamTypes(setter1, type);
214 setTypes.put(property, Map.entry(paramTypes[0], typeToClass(paramTypes[0])));
215 return null;
216 }
217
218 private void addSetMethod(String name, Method method) {
219 MethodInvoker invoker = new MethodInvoker(method);
220 setMethods.put(name, invoker);
221 Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
222 setTypes.put(name, Map.entry(paramTypes[0], typeToClass(paramTypes[0])));
223 }
224
225 private Class<?> typeToClass(Type src) {
226 if (src instanceof Class) {
227 return (Class<?>) src;
228 } else if (src instanceof ParameterizedType) {
229 return (Class<?>) ((ParameterizedType) src).getRawType();
230 } else if (src instanceof GenericArrayType) {
231 Type componentType = ((GenericArrayType) src).getGenericComponentType();
232 if (componentType instanceof Class) {
233 return Array.newInstance((Class<?>) componentType, 0).getClass();
234 } else {
235 Class<?> componentClass = typeToClass(componentType);
236 return Array.newInstance(componentClass, 0).getClass();
237 }
238 }
239 return Object.class;
240 }
241
242 private void addFields(Class<?> clazz) {
243 Field[] fields = clazz.getDeclaredFields();
244 for (Field field : fields) {
245 if (!setMethods.containsKey(field.getName())) {
246
247
248
249 int modifiers = field.getModifiers();
250 if (!Modifier.isFinal(modifiers) || !Modifier.isStatic(modifiers)) {
251 addSetField(field);
252 }
253 }
254 if (!getMethods.containsKey(field.getName())) {
255 addGetField(field);
256 }
257 }
258 if (clazz.getSuperclass() != null) {
259 addFields(clazz.getSuperclass());
260 }
261 }
262
263 private void addSetField(Field field) {
264 if (isValidPropertyName(field.getName())) {
265 setMethods.put(field.getName(), new SetFieldInvoker(field));
266 Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
267 setTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
268 }
269 }
270
271 private void addGetField(Field field) {
272 if (isValidPropertyName(field.getName())) {
273 getMethods.put(field.getName(), new GetFieldInvoker(field));
274 Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
275 getTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
276 }
277 }
278
279 private boolean isValidPropertyName(String name) {
280 return !name.startsWith("$") && !"serialVersionUID".equals(name) && !"class".equals(name);
281 }
282
283
284
285
286
287
288
289
290
291
292 private Method[] getClassMethods(Class<?> clazz) {
293 Map<String, Method> uniqueMethods = new HashMap<>();
294 Class<?> currentClass = clazz;
295 while (currentClass != null && currentClass != Object.class) {
296 addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
297
298
299
300 Class<?>[] interfaces = currentClass.getInterfaces();
301 for (Class<?> anInterface : interfaces) {
302 addUniqueMethods(uniqueMethods, anInterface.getMethods());
303 }
304
305 currentClass = currentClass.getSuperclass();
306 }
307
308 Collection<Method> methods = uniqueMethods.values();
309
310 return methods.toArray(new Method[0]);
311 }
312
313 private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
314 for (Method currentMethod : methods) {
315 if (!currentMethod.isBridge()) {
316 String signature = getSignature(currentMethod);
317
318
319
320 if (!uniqueMethods.containsKey(signature)) {
321 uniqueMethods.put(signature, currentMethod);
322 }
323 }
324 }
325 }
326
327 private String getSignature(Method method) {
328 StringBuilder sb = new StringBuilder();
329 Class<?> returnType = method.getReturnType();
330 sb.append(returnType.getName()).append('#');
331 sb.append(method.getName());
332 Class<?>[] parameters = method.getParameterTypes();
333 for (int i = 0; i < parameters.length; i++) {
334 sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
335 }
336 return sb.toString();
337 }
338
339
340
341
342
343
344
345
346 public static boolean canControlMemberAccessible() {
347 try {
348 SecurityManager securityManager = System.getSecurityManager();
349 if (null != securityManager) {
350 securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
351 }
352 } catch (SecurityException e) {
353 return false;
354 }
355 return true;
356 }
357
358
359
360
361
362
363 public Class<?> getType() {
364 return clazz;
365 }
366
367 public Constructor<?> getDefaultConstructor() {
368 if (defaultConstructor != null) {
369 return defaultConstructor;
370 }
371 throw new ReflectionException("There is no default constructor for " + clazz);
372 }
373
374 public boolean hasDefaultConstructor() {
375 return defaultConstructor != null;
376 }
377
378 public Invoker getSetInvoker(String propertyName) {
379 Invoker method = setMethods.get(propertyName);
380 if (method == null) {
381 throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + clazz + "'");
382 }
383 return method;
384 }
385
386 public Invoker getGetInvoker(String propertyName) {
387 Invoker method = getMethods.get(propertyName);
388 if (method == null) {
389 throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + clazz + "'");
390 }
391 return method;
392 }
393
394
395
396
397
398
399
400
401
402 public Class<?> getSetterType(String propertyName) {
403 Class<?> clazz = setTypes.getOrDefault(propertyName, nullEntry).getValue();
404 if (clazz == null) {
405 throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + clazz + "'");
406 }
407 return clazz;
408 }
409
410 public Entry<Type, Class<?>> getGenericSetterType(String propertyName) {
411 return setTypes.computeIfAbsent(propertyName, k -> {
412 throw new ReflectionException("There is no setter for property named '" + k + "' in '" + clazz + "'");
413 });
414 }
415
416
417
418
419
420
421
422
423
424 public Class<?> getGetterType(String propertyName) {
425 Class<?> clazz = getTypes.getOrDefault(propertyName, nullEntry).getValue();
426 if (clazz == null) {
427 throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + clazz + "'");
428 }
429 return clazz;
430 }
431
432 public Entry<Type, Class<?>> getGenericGetterType(String propertyName) {
433 return getTypes.computeIfAbsent(propertyName, k -> {
434 throw new ReflectionException("There is no getter for property named '" + k + "' in '" + clazz + "'");
435 });
436 }
437
438
439
440
441
442
443 public String[] getGetablePropertyNames() {
444 return readablePropertyNames;
445 }
446
447
448
449
450
451
452 public String[] getSetablePropertyNames() {
453 return writablePropertyNames;
454 }
455
456
457
458
459
460
461
462
463
464 public boolean hasSetter(String propertyName) {
465 return setMethods.containsKey(propertyName);
466 }
467
468
469
470
471
472
473
474
475
476 public boolean hasGetter(String propertyName) {
477 return getMethods.containsKey(propertyName);
478 }
479
480 public String findPropertyName(String name) {
481 return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
482 }
483
484
485
486
487 private static boolean isRecord(Class<?> clazz) {
488 try {
489 return isRecordMethodHandle != null && (boolean) isRecordMethodHandle.invokeExact(clazz);
490 } catch (Throwable e) {
491 throw new ReflectionException("Failed to invoke 'Class.isRecord()'.", e);
492 }
493 }
494
495 private static MethodHandle getIsRecordMethodHandle() {
496 MethodHandles.Lookup lookup = MethodHandles.lookup();
497 MethodType mt = MethodType.methodType(boolean.class);
498 try {
499 return lookup.findVirtual(Class.class, "isRecord", mt);
500 } catch (NoSuchMethodException | IllegalAccessException e) {
501 return null;
502 }
503 }
504 }