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

mybatis / mybatis-3 / 2985

05 Oct 2025 01:09AM UTC coverage: 87.38% (-0.009%) from 87.389%
2985

Pull #3540

github

web-flow
fix(deps): update dependency org.mybatis:mybatis-parent to v51
Pull Request #3540: fix(deps): update dependency org.mybatis:mybatis-parent to v51

3849 of 4663 branches covered (82.54%)

9943 of 11379 relevant lines covered (87.38%)

0.87 hits per line

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

91.82
/src/main/java/org/apache/ibatis/reflection/Reflector.java
1
/*
2
 *    Copyright 2009-2025 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.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
 * 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 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<>();
1✔
62
  private final Map<String, Invoker> getMethods = new HashMap<>();
1✔
63
  private final Map<String, Entry<Type, Class<?>>> setTypes = new HashMap<>();
1✔
64
  private final Map<String, Entry<Type, Class<?>>> getTypes = new HashMap<>();
1✔
65
  private Constructor<?> defaultConstructor;
66

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

69
  private static final Entry<Type, Class<?>> nullEntry = new AbstractMap.SimpleImmutableEntry<>(null, null);
1✔
70

71
  public Reflector(Type type) {
1✔
72
    this.type = type;
1✔
73
    if (type instanceof ParameterizedType) {
1✔
74
      this.clazz = (Class<?>) ((ParameterizedType) type).getRawType();
1✔
75
    } else {
76
      this.clazz = (Class<?>) type;
1✔
77
    }
78
    addDefaultConstructor(clazz);
1✔
79
    Method[] classMethods = getClassMethods(clazz);
1✔
80
    if (isRecord(clazz)) {
1✔
81
      addRecordGetMethods(classMethods);
1✔
82
    } else {
83
      addGetMethods(classMethods);
1✔
84
      addSetMethods(classMethods);
1✔
85
      addFields(clazz);
1✔
86
    }
87
    readablePropertyNames = getMethods.keySet().toArray(new String[0]);
1✔
88
    writablePropertyNames = setMethods.keySet().toArray(new String[0]);
1✔
89
    for (String propName : readablePropertyNames) {
1✔
90
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
1✔
91
    }
92
    for (String propName : writablePropertyNames) {
1✔
93
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
1✔
94
    }
95
  }
1✔
96

97
  private void addRecordGetMethods(Method[] methods) {
98
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0)
1✔
99
        .forEach(m -> addGetMethod(m.getName(), m, false));
1✔
100
  }
1✔
101

102
  private void addDefaultConstructor(Class<?> clazz) {
103
    Constructor<?>[] constructors = clazz.getDeclaredConstructors();
1✔
104
    Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0).findAny()
1✔
105
        .ifPresent(constructor -> this.defaultConstructor = constructor);
1✔
106
  }
1✔
107

108
  private void addGetMethods(Method[] methods) {
109
    Map<String, List<Method>> conflictingGetters = new HashMap<>();
1✔
110
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
1✔
111
        .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
112
    resolveGetterConflicts(conflictingGetters);
1✔
113
  }
1✔
114

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

148
  private void addGetMethod(String name, Method method, boolean isAmbiguous) {
149
    MethodInvoker invoker = isAmbiguous ? new AmbiguousMethodInvoker(method, MessageFormat.format(
1✔
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);
1✔
152
    getMethods.put(name, invoker);
1✔
153
    Type returnType = TypeParameterResolver.resolveReturnType(method, type);
1✔
154
    getTypes.put(name, Map.entry(returnType, typeToClass(returnType)));
1✔
155
  }
1✔
156

157
  private void addSetMethods(Method[] methods) {
158
    Map<String, List<Method>> conflictingSetters = new HashMap<>();
1✔
159
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 1 && PropertyNamer.isSetter(m.getName()))
1✔
160
        .forEach(m -> addMethodConflict(conflictingSetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
161
    resolveSetterConflicts(conflictingSetters);
1✔
162
  }
1✔
163

164
  private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
165
    if (isValidPropertyName(name)) {
1!
166
      List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
1✔
167
      list.add(method);
1✔
168
    }
169
  }
1✔
170

171
  private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
172
    for (Entry<String, List<Method>> entry : conflictingSetters.entrySet()) {
1✔
173
      String propName = entry.getKey();
1✔
174
      List<Method> setters = entry.getValue();
1✔
175
      Class<?> getterType = getTypes.getOrDefault(propName, nullEntry).getValue();
1✔
176
      boolean isGetterAmbiguous = getMethods.get(propName) instanceof AmbiguousMethodInvoker;
1✔
177
      boolean isSetterAmbiguous = false;
1✔
178
      Method match = null;
1✔
179
      for (Method setter : setters) {
1✔
180
        if (!isGetterAmbiguous && setter.getParameterTypes()[0].equals(getterType)) {
1✔
181
          // should be the best match
182
          match = setter;
1✔
183
          break;
1✔
184
        }
185
        if (!isSetterAmbiguous) {
1✔
186
          match = pickBetterSetter(match, setter, propName);
1✔
187
          isSetterAmbiguous = match == null;
1✔
188
        }
189
      }
1✔
190
      if (match != null) {
1✔
191
        addSetMethod(propName, match);
1✔
192
      }
193
    }
1✔
194
  }
1✔
195

196
  private Method pickBetterSetter(Method setter1, Method setter2, String property) {
197
    if (setter1 == null) {
1✔
198
      return setter2;
1✔
199
    }
200
    Class<?> paramType1 = setter1.getParameterTypes()[0];
1✔
201
    Class<?> paramType2 = setter2.getParameterTypes()[0];
1✔
202
    if (paramType1.isAssignableFrom(paramType2)) {
1!
203
      return setter2;
×
204
    }
205
    if (paramType2.isAssignableFrom(paramType1)) {
1✔
206
      return setter1;
1✔
207
    }
208
    MethodInvoker invoker = new AmbiguousMethodInvoker(setter1,
1✔
209
        MessageFormat.format(
1✔
210
            "Ambiguous setters defined for property ''{0}'' in class ''{1}'' with types ''{2}'' and ''{3}''.", property,
211
            setter2.getDeclaringClass().getName(), paramType1.getName(), paramType2.getName()));
1✔
212
    setMethods.put(property, invoker);
1✔
213
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(setter1, type);
1✔
214
    setTypes.put(property, Map.entry(paramTypes[0], typeToClass(paramTypes[0])));
1✔
215
    return null;
1✔
216
  }
217

218
  private void addSetMethod(String name, Method method) {
219
    MethodInvoker invoker = new MethodInvoker(method);
1✔
220
    setMethods.put(name, invoker);
1✔
221
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
1✔
222
    setTypes.put(name, Map.entry(paramTypes[0], typeToClass(paramTypes[0])));
1✔
223
  }
1✔
224

225
  private Class<?> typeToClass(Type src) {
226
    if (src instanceof Class) {
1✔
227
      return (Class<?>) src;
1✔
228
    } else if (src instanceof ParameterizedType) {
1✔
229
      return (Class<?>) ((ParameterizedType) src).getRawType();
1✔
230
    } else if (src instanceof GenericArrayType) {
1!
231
      Type componentType = ((GenericArrayType) src).getGenericComponentType();
1✔
232
      if (componentType instanceof Class) {
1!
233
        return Array.newInstance((Class<?>) componentType, 0).getClass();
×
234
      } else {
235
        Class<?> componentClass = typeToClass(componentType);
1✔
236
        return Array.newInstance(componentClass, 0).getClass();
1✔
237
      }
238
    }
239
    return Object.class;
×
240
  }
241

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

263
  private void addSetField(Field field) {
264
    if (isValidPropertyName(field.getName())) {
1!
265
      setMethods.put(field.getName(), new SetFieldInvoker(field));
1✔
266
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
267
      setTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
1✔
268
    }
269
  }
1✔
270

271
  private void addGetField(Field field) {
272
    if (isValidPropertyName(field.getName())) {
1✔
273
      getMethods.put(field.getName(), new GetFieldInvoker(field));
1✔
274
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
275
      getTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
1✔
276
    }
277
  }
1✔
278

279
  private boolean isValidPropertyName(String name) {
280
    return !name.startsWith("$") && !"serialVersionUID".equals(name) && !"class".equals(name);
1!
281
  }
282

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

298
      // we also need to look for interface methods -
299
      // because the class may be abstract
300
      Class<?>[] interfaces = currentClass.getInterfaces();
1✔
301
      for (Class<?> anInterface : interfaces) {
1✔
302
        addUniqueMethods(uniqueMethods, anInterface.getMethods());
1✔
303
      }
304

305
      currentClass = currentClass.getSuperclass();
1✔
306
    }
1✔
307

308
    Collection<Method> methods = uniqueMethods.values();
1✔
309

310
    return methods.toArray(new Method[0]);
1✔
311
  }
312

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

327
  private String getSignature(Method method) {
328
    StringBuilder sb = new StringBuilder();
1✔
329
    Class<?> returnType = method.getReturnType();
1✔
330
    sb.append(returnType.getName()).append('#');
1✔
331
    sb.append(method.getName());
1✔
332
    Class<?>[] parameters = method.getParameterTypes();
1✔
333
    for (int i = 0; i < parameters.length; i++) {
1✔
334
      sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
1✔
335
    }
336
    return sb.toString();
1✔
337
  }
338

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

358
  /**
359
   * Gets the name of the class the instance provides information for.
360
   *
361
   * @return The class name
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;
1✔
376
  }
377

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

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

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

410
  public Entry<Type, Class<?>> getGenericSetterType(String propertyName) {
411
    return setTypes.computeIfAbsent(propertyName, k -> {
1✔
412
      throw new ReflectionException("There is no setter for property named '" + k + "' in '" + clazz + "'");
1✔
413
    });
414
  }
415

416
  /**
417
   * Gets the type for a property getter.
418
   *
419
   * @param propertyName
420
   *          - the name of the property
421
   *
422
   * @return The Class of the property getter
423
   */
424
  public Class<?> getGetterType(String propertyName) {
425
    Class<?> clazz = getTypes.getOrDefault(propertyName, nullEntry).getValue();
1✔
426
    if (clazz == null) {
1!
427
      throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + clazz + "'");
×
428
    }
429
    return clazz;
1✔
430
  }
431

432
  public Entry<Type, Class<?>> getGenericGetterType(String propertyName) {
433
    return getTypes.computeIfAbsent(propertyName, k -> {
1✔
434
      throw new ReflectionException("There is no getter for property named '" + k + "' in '" + clazz + "'");
1✔
435
    });
436
  }
437

438
  /**
439
   * Gets an array of the readable properties for an object.
440
   *
441
   * @return The array
442
   */
443
  public String[] getGetablePropertyNames() {
444
    return readablePropertyNames;
1✔
445
  }
446

447
  /**
448
   * Gets an array of the writable properties for an object.
449
   *
450
   * @return The array
451
   */
452
  public String[] getSetablePropertyNames() {
453
    return writablePropertyNames;
1✔
454
  }
455

456
  /**
457
   * Check to see if a class has a writable property by name.
458
   *
459
   * @param propertyName
460
   *          - the name of the property to check
461
   *
462
   * @return True if the object has a writable property by the name
463
   */
464
  public boolean hasSetter(String propertyName) {
465
    return setMethods.containsKey(propertyName);
1✔
466
  }
467

468
  /**
469
   * Check to see if a class has a readable property by name.
470
   *
471
   * @param propertyName
472
   *          - the name of the property to check
473
   *
474
   * @return True if the object has a readable property by the name
475
   */
476
  public boolean hasGetter(String propertyName) {
477
    return getMethods.containsKey(propertyName);
1✔
478
  }
479

480
  public String findPropertyName(String name) {
481
    return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
1✔
482
  }
483

484
  /**
485
   * Class.isRecord() alternative for Java 15 and older.
486
   */
487
  private static boolean isRecord(Class<?> clazz) {
488
    try {
489
      return isRecordMethodHandle != null && (boolean) isRecordMethodHandle.invokeExact(clazz);
1!
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();
1✔
497
    MethodType mt = MethodType.methodType(boolean.class);
1✔
498
    try {
499
      return lookup.findVirtual(Class.class, "isRecord", mt);
1✔
500
    } catch (NoSuchMethodException | IllegalAccessException e) {
×
501
      return null;
×
502
    }
503
  }
504
}
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