• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mybatis / mybatis-3 / #2982

pending completion
#2982

push

github

web-flow
Merge pull request #2798 from hazendaz/formatting

[ci] formatting

31 of 31 new or added lines in 2 files covered. (100.0%)

9382 of 10751 relevant lines covered (87.27%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.67
/src/main/java/org/apache/ibatis/reflection/Reflector.java
1
/*
2
 *    Copyright 2009-2023 the original author or authors.
3
 *
4
 *    Licensed under the Apache License, Version 2.0 (the "License");
5
 *    you may not use this file except in compliance with the License.
6
 *    You may obtain a copy of the License at
7
 *
8
 *       https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *    Unless required by applicable law or agreed to in writing, software
11
 *    distributed under the License is distributed on an "AS IS" BASIS,
12
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *    See the License for the specific language governing permissions and
14
 *    limitations under the License.
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.ArrayList;
32
import java.util.Arrays;
33
import java.util.Collection;
34
import java.util.HashMap;
35
import java.util.List;
36
import java.util.Locale;
37
import java.util.Map;
38
import java.util.Map.Entry;
39

40
import org.apache.ibatis.reflection.invoker.AmbiguousMethodInvoker;
41
import org.apache.ibatis.reflection.invoker.GetFieldInvoker;
42
import org.apache.ibatis.reflection.invoker.Invoker;
43
import org.apache.ibatis.reflection.invoker.MethodInvoker;
44
import org.apache.ibatis.reflection.invoker.SetFieldInvoker;
45
import org.apache.ibatis.reflection.property.PropertyNamer;
46
import org.apache.ibatis.util.MapUtil;
47

48
/**
49
 * This class represents a cached set of class definition information that allows for easy mapping between property
50
 * names and getter/setter methods.
51
 *
52
 * @author Clinton Begin
53
 */
54
public class Reflector {
55

56
  private static final MethodHandle isRecordMethodHandle = getIsRecordMethodHandle();
1✔
57
  private final Class<?> type;
58
  private final String[] readablePropertyNames;
59
  private final String[] writablePropertyNames;
60
  private final Map<String, Invoker> setMethods = new HashMap<>();
1✔
61
  private final Map<String, Invoker> getMethods = new HashMap<>();
1✔
62
  private final Map<String, Class<?>> setTypes = new HashMap<>();
1✔
63
  private final Map<String, Class<?>> getTypes = new HashMap<>();
1✔
64
  private Constructor<?> defaultConstructor;
65

66
  private Map<String, String> caseInsensitivePropertyMap = new HashMap<>();
1✔
67

68
  public Reflector(Class<?> clazz) {
1✔
69
    type = clazz;
1✔
70
    addDefaultConstructor(clazz);
1✔
71
    Method[] classMethods = getClassMethods(clazz);
1✔
72
    if (isRecord(type)) {
1✔
73
      addRecordGetMethods(classMethods);
×
74
    } else {
75
      addGetMethods(classMethods);
1✔
76
      addSetMethods(classMethods);
1✔
77
      addFields(clazz);
1✔
78
    }
79
    readablePropertyNames = getMethods.keySet().toArray(new String[0]);
1✔
80
    writablePropertyNames = setMethods.keySet().toArray(new String[0]);
1✔
81
    for (String propName : readablePropertyNames) {
1✔
82
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
1✔
83
    }
84
    for (String propName : writablePropertyNames) {
1✔
85
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
1✔
86
    }
87
  }
1✔
88

89
  private void addRecordGetMethods(Method[] methods) {
90
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0)
×
91
        .forEach(m -> addGetMethod(m.getName(), m, false));
×
92
  }
×
93

94
  private void addDefaultConstructor(Class<?> clazz) {
95
    Constructor<?>[] constructors = clazz.getDeclaredConstructors();
1✔
96
    Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0).findAny()
1✔
97
        .ifPresent(constructor -> this.defaultConstructor = constructor);
1✔
98
  }
1✔
99

100
  private void addGetMethods(Method[] methods) {
101
    Map<String, List<Method>> conflictingGetters = new HashMap<>();
1✔
102
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
1✔
103
        .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
104
    resolveGetterConflicts(conflictingGetters);
1✔
105
  }
1✔
106

107
  private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
108
    for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
1✔
109
      Method winner = null;
1✔
110
      String propName = entry.getKey();
1✔
111
      boolean isAmbiguous = false;
1✔
112
      for (Method candidate : entry.getValue()) {
1✔
113
        if (winner == null) {
1✔
114
          winner = candidate;
1✔
115
          continue;
1✔
116
        }
117
        Class<?> winnerType = winner.getReturnType();
1✔
118
        Class<?> candidateType = candidate.getReturnType();
1✔
119
        if (candidateType.equals(winnerType)) {
1✔
120
          if (!boolean.class.equals(candidateType)) {
1✔
121
            isAmbiguous = true;
1✔
122
            break;
1✔
123
          } else if (candidate.getName().startsWith("is")) {
1✔
124
            winner = candidate;
×
125
          }
126
        } else if (candidateType.isAssignableFrom(winnerType)) {
1✔
127
          // OK getter type is descendant
128
        } else if (winnerType.isAssignableFrom(candidateType)) {
1✔
129
          winner = candidate;
1✔
130
        } else {
131
          isAmbiguous = true;
1✔
132
          break;
1✔
133
        }
134
      }
1✔
135
      addGetMethod(propName, winner, isAmbiguous);
1✔
136
    }
1✔
137
  }
1✔
138

139
  private void addGetMethod(String name, Method method, boolean isAmbiguous) {
140
    MethodInvoker invoker = isAmbiguous ? new AmbiguousMethodInvoker(method, MessageFormat.format(
1✔
141
        "Illegal overloaded getter method with ambiguous type for property ''{0}'' in class ''{1}''. This breaks the JavaBeans specification and can cause unpredictable results.",
142
        name, method.getDeclaringClass().getName())) : new MethodInvoker(method);
1✔
143
    getMethods.put(name, invoker);
1✔
144
    Type returnType = TypeParameterResolver.resolveReturnType(method, type);
1✔
145
    getTypes.put(name, typeToClass(returnType));
1✔
146
  }
1✔
147

148
  private void addSetMethods(Method[] methods) {
149
    Map<String, List<Method>> conflictingSetters = new HashMap<>();
1✔
150
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 1 && PropertyNamer.isSetter(m.getName()))
1✔
151
        .forEach(m -> addMethodConflict(conflictingSetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
152
    resolveSetterConflicts(conflictingSetters);
1✔
153
  }
1✔
154

155
  private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
156
    if (isValidPropertyName(name)) {
1✔
157
      List<Method> list = MapUtil.computeIfAbsent(conflictingMethods, name, k -> new ArrayList<>());
1✔
158
      list.add(method);
1✔
159
    }
160
  }
1✔
161

162
  private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
163
    for (Entry<String, List<Method>> entry : conflictingSetters.entrySet()) {
1✔
164
      String propName = entry.getKey();
1✔
165
      List<Method> setters = entry.getValue();
1✔
166
      Class<?> getterType = getTypes.get(propName);
1✔
167
      boolean isGetterAmbiguous = getMethods.get(propName) instanceof AmbiguousMethodInvoker;
1✔
168
      boolean isSetterAmbiguous = false;
1✔
169
      Method match = null;
1✔
170
      for (Method setter : setters) {
1✔
171
        if (!isGetterAmbiguous && setter.getParameterTypes()[0].equals(getterType)) {
1✔
172
          // should be the best match
173
          match = setter;
1✔
174
          break;
1✔
175
        }
176
        if (!isSetterAmbiguous) {
1✔
177
          match = pickBetterSetter(match, setter, propName);
1✔
178
          isSetterAmbiguous = match == null;
1✔
179
        }
180
      }
1✔
181
      if (match != null) {
1✔
182
        addSetMethod(propName, match);
1✔
183
      }
184
    }
1✔
185
  }
1✔
186

187
  private Method pickBetterSetter(Method setter1, Method setter2, String property) {
188
    if (setter1 == null) {
1✔
189
      return setter2;
1✔
190
    }
191
    Class<?> paramType1 = setter1.getParameterTypes()[0];
1✔
192
    Class<?> paramType2 = setter2.getParameterTypes()[0];
1✔
193
    if (paramType1.isAssignableFrom(paramType2)) {
1✔
194
      return setter2;
×
195
    } else if (paramType2.isAssignableFrom(paramType1)) {
1✔
196
      return setter1;
1✔
197
    }
198
    MethodInvoker invoker = new AmbiguousMethodInvoker(setter1,
1✔
199
        MessageFormat.format(
1✔
200
            "Ambiguous setters defined for property ''{0}'' in class ''{1}'' with types ''{2}'' and ''{3}''.", property,
201
            setter2.getDeclaringClass().getName(), paramType1.getName(), paramType2.getName()));
1✔
202
    setMethods.put(property, invoker);
1✔
203
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(setter1, type);
1✔
204
    setTypes.put(property, typeToClass(paramTypes[0]));
1✔
205
    return null;
1✔
206
  }
207

208
  private void addSetMethod(String name, Method method) {
209
    MethodInvoker invoker = new MethodInvoker(method);
1✔
210
    setMethods.put(name, invoker);
1✔
211
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
1✔
212
    setTypes.put(name, typeToClass(paramTypes[0]));
1✔
213
  }
1✔
214

215
  private Class<?> typeToClass(Type src) {
216
    Class<?> result = null;
1✔
217
    if (src instanceof Class) {
1✔
218
      result = (Class<?>) src;
1✔
219
    } else if (src instanceof ParameterizedType) {
1✔
220
      result = (Class<?>) ((ParameterizedType) src).getRawType();
1✔
221
    } else if (src instanceof GenericArrayType) {
1✔
222
      Type componentType = ((GenericArrayType) src).getGenericComponentType();
1✔
223
      if (componentType instanceof Class) {
1✔
224
        result = Array.newInstance((Class<?>) componentType, 0).getClass();
×
225
      } else {
226
        Class<?> componentClass = typeToClass(componentType);
1✔
227
        result = Array.newInstance(componentClass, 0).getClass();
1✔
228
      }
229
    }
230
    if (result == null) {
1✔
231
      result = Object.class;
×
232
    }
233
    return result;
1✔
234
  }
235

236
  private void addFields(Class<?> clazz) {
237
    Field[] fields = clazz.getDeclaredFields();
1✔
238
    for (Field field : fields) {
1✔
239
      if (!setMethods.containsKey(field.getName())) {
1✔
240
        // issue #379 - removed the check for final because JDK 1.5 allows
241
        // modification of final fields through reflection (JSR-133). (JGB)
242
        // pr #16 - final static can only be set by the classloader
243
        int modifiers = field.getModifiers();
1✔
244
        if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
1✔
245
          addSetField(field);
1✔
246
        }
247
      }
248
      if (!getMethods.containsKey(field.getName())) {
1✔
249
        addGetField(field);
1✔
250
      }
251
    }
252
    if (clazz.getSuperclass() != null) {
1✔
253
      addFields(clazz.getSuperclass());
1✔
254
    }
255
  }
1✔
256

257
  private void addSetField(Field field) {
258
    if (isValidPropertyName(field.getName())) {
1✔
259
      setMethods.put(field.getName(), new SetFieldInvoker(field));
1✔
260
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
261
      setTypes.put(field.getName(), typeToClass(fieldType));
1✔
262
    }
263
  }
1✔
264

265
  private void addGetField(Field field) {
266
    if (isValidPropertyName(field.getName())) {
1✔
267
      getMethods.put(field.getName(), new GetFieldInvoker(field));
1✔
268
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
269
      getTypes.put(field.getName(), typeToClass(fieldType));
1✔
270
    }
271
  }
1✔
272

273
  private boolean isValidPropertyName(String name) {
274
    return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
1✔
275
  }
276

277
  /**
278
   * This method returns an array containing all methods declared in this class and any superclass. We use this method,
279
   * instead of the simpler <code>Class.getMethods()</code>, because we want to look for private methods as well.
280
   *
281
   * @param clazz
282
   *          The class
283
   *
284
   * @return An array containing all methods in this class
285
   */
286
  private Method[] getClassMethods(Class<?> clazz) {
287
    Map<String, Method> uniqueMethods = new HashMap<>();
1✔
288
    Class<?> currentClass = clazz;
1✔
289
    while (currentClass != null && currentClass != Object.class) {
1✔
290
      addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
1✔
291

292
      // we also need to look for interface methods -
293
      // because the class may be abstract
294
      Class<?>[] interfaces = currentClass.getInterfaces();
1✔
295
      for (Class<?> anInterface : interfaces) {
1✔
296
        addUniqueMethods(uniqueMethods, anInterface.getMethods());
1✔
297
      }
298

299
      currentClass = currentClass.getSuperclass();
1✔
300
    }
1✔
301

302
    Collection<Method> methods = uniqueMethods.values();
1✔
303

304
    return methods.toArray(new Method[0]);
1✔
305
  }
306

307
  private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
308
    for (Method currentMethod : methods) {
1✔
309
      if (!currentMethod.isBridge()) {
1✔
310
        String signature = getSignature(currentMethod);
1✔
311
        // check to see if the method is already known
312
        // if it is known, then an extended class must have
313
        // overridden a method
314
        if (!uniqueMethods.containsKey(signature)) {
1✔
315
          uniqueMethods.put(signature, currentMethod);
1✔
316
        }
317
      }
318
    }
319
  }
1✔
320

321
  private String getSignature(Method method) {
322
    StringBuilder sb = new StringBuilder();
1✔
323
    Class<?> returnType = method.getReturnType();
1✔
324
    if (returnType != null) {
1✔
325
      sb.append(returnType.getName()).append('#');
1✔
326
    }
327
    sb.append(method.getName());
1✔
328
    Class<?>[] parameters = method.getParameterTypes();
1✔
329
    for (int i = 0; i < parameters.length; i++) {
1✔
330
      sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
1✔
331
    }
332
    return sb.toString();
1✔
333
  }
334

335
  /**
336
   * Checks whether can control member accessible.
337
   *
338
   * @return If can control member accessible, it return {@literal true}
339
   *
340
   * @since 3.5.0
341
   */
342
  public static boolean canControlMemberAccessible() {
343
    try {
344
      SecurityManager securityManager = System.getSecurityManager();
1✔
345
      if (null != securityManager) {
1✔
346
        securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
×
347
      }
348
    } catch (SecurityException e) {
×
349
      return false;
×
350
    }
1✔
351
    return true;
1✔
352
  }
353

354
  /**
355
   * Gets the name of the class the instance provides information for.
356
   *
357
   * @return The class name
358
   */
359
  public Class<?> getType() {
360
    return type;
1✔
361
  }
362

363
  public Constructor<?> getDefaultConstructor() {
364
    if (defaultConstructor != null) {
×
365
      return defaultConstructor;
×
366
    } else {
367
      throw new ReflectionException("There is no default constructor for " + type);
×
368
    }
369
  }
370

371
  public boolean hasDefaultConstructor() {
372
    return defaultConstructor != null;
1✔
373
  }
374

375
  public Invoker getSetInvoker(String propertyName) {
376
    Invoker method = setMethods.get(propertyName);
1✔
377
    if (method == null) {
1✔
378
      throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
×
379
    }
380
    return method;
1✔
381
  }
382

383
  public Invoker getGetInvoker(String propertyName) {
384
    Invoker method = getMethods.get(propertyName);
1✔
385
    if (method == null) {
1✔
386
      throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
1✔
387
    }
388
    return method;
1✔
389
  }
390

391
  /**
392
   * Gets the type for a property setter.
393
   *
394
   * @param propertyName
395
   *          - the name of the property
396
   *
397
   * @return The Class of the property setter
398
   */
399
  public Class<?> getSetterType(String propertyName) {
400
    Class<?> clazz = setTypes.get(propertyName);
1✔
401
    if (clazz == null) {
1✔
402
      throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
1✔
403
    }
404
    return clazz;
1✔
405
  }
406

407
  /**
408
   * Gets the type for a property getter.
409
   *
410
   * @param propertyName
411
   *          - the name of the property
412
   *
413
   * @return The Class of the property getter
414
   */
415
  public Class<?> getGetterType(String propertyName) {
416
    Class<?> clazz = getTypes.get(propertyName);
1✔
417
    if (clazz == null) {
1✔
418
      throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
1✔
419
    }
420
    return clazz;
1✔
421
  }
422

423
  /**
424
   * Gets an array of the readable properties for an object.
425
   *
426
   * @return The array
427
   */
428
  public String[] getGetablePropertyNames() {
429
    return readablePropertyNames;
1✔
430
  }
431

432
  /**
433
   * Gets an array of the writable properties for an object.
434
   *
435
   * @return The array
436
   */
437
  public String[] getSetablePropertyNames() {
438
    return writablePropertyNames;
1✔
439
  }
440

441
  /**
442
   * Check to see if a class has a writable property by name.
443
   *
444
   * @param propertyName
445
   *          - the name of the property to check
446
   *
447
   * @return True if the object has a writable property by the name
448
   */
449
  public boolean hasSetter(String propertyName) {
450
    return setMethods.containsKey(propertyName);
1✔
451
  }
452

453
  /**
454
   * Check to see if a class has a readable property by name.
455
   *
456
   * @param propertyName
457
   *          - the name of the property to check
458
   *
459
   * @return True if the object has a readable property by the name
460
   */
461
  public boolean hasGetter(String propertyName) {
462
    return getMethods.containsKey(propertyName);
1✔
463
  }
464

465
  public String findPropertyName(String name) {
466
    return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
1✔
467
  }
468

469
  /**
470
   * Class.isRecord() alternative for Java 15 and older.
471
   */
472
  private static boolean isRecord(Class<?> clazz) {
473
    try {
474
      return isRecordMethodHandle != null && (boolean) isRecordMethodHandle.invokeExact(clazz);
1✔
475
    } catch (Throwable e) {
×
476
      throw new ReflectionException("Failed to invoke 'Class.isRecord()'.", e);
×
477
    }
478
  }
479

480
  private static MethodHandle getIsRecordMethodHandle() {
481
    MethodHandles.Lookup lookup = MethodHandles.lookup();
1✔
482
    MethodType mt = MethodType.methodType(boolean.class);
1✔
483
    try {
484
      return lookup.findVirtual(Class.class, "isRecord", mt);
×
485
    } catch (NoSuchMethodException | IllegalAccessException e) {
1✔
486
      return null;
1✔
487
    }
488
  }
489
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc