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

mybatis / mybatis-3 / 3060

13 Dec 2025 08:30AM UTC coverage: 87.389%. Remained the same
3060

Pull #3551

github

web-flow
Merge c9c637dc2 into 58e2d5e9b
Pull Request #3551: fix: Reflector should reflect record

3844 of 4659 branches covered (82.51%)

9 of 10 new or added lines in 1 file covered. (90.0%)

6 existing lines in 1 file now uncovered.

9951 of 11387 relevant lines covered (87.39%)

0.87 hits per line

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

92.04
/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
    if (isRecord(clazz)) {
1✔
80
      addRecordGetMethods(clazz);
1✔
81
    } else {
82
      Method[] classMethods = getClassMethods(clazz);
1✔
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(Class<?> recordClass) {
98
    Arrays.stream(recordClass.getDeclaredFields()).filter(field -> !Modifier.isStatic(field.getModifiers()))
1!
99
        .forEach(field -> {
1✔
100
          try {
101
            String fieldName = field.getName();
1✔
102
            // record's get method and field have the same name
103
            Method m = recordClass.getMethod(fieldName);
1✔
104
            addGetMethod(fieldName, m, false);
1✔
NEW
105
          } catch (NoSuchMethodException ignore) {
×
106
            // A standard record can never throw this exception
107
          }
1✔
108
        });
1✔
109
  }
1✔
110

111
  private void addDefaultConstructor(Class<?> clazz) {
112
    Constructor<?>[] constructors = clazz.getDeclaredConstructors();
1✔
113
    Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0).findAny()
1✔
114
        .ifPresent(constructor -> this.defaultConstructor = constructor);
1✔
115
  }
1✔
116

117
  private void addGetMethods(Method[] methods) {
118
    Map<String, List<Method>> conflictingGetters = new HashMap<>();
1✔
119
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
1✔
120
        .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
121
    resolveGetterConflicts(conflictingGetters);
1✔
122
  }
1✔
123

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

157
  private void addGetMethod(String name, Method method, boolean isAmbiguous) {
158
    MethodInvoker invoker = isAmbiguous ? new AmbiguousMethodInvoker(method, MessageFormat.format(
1✔
159
        "Illegal overloaded getter method with ambiguous type for property ''{0}'' in class ''{1}''. This breaks the JavaBeans specification and can cause unpredictable results.",
160
        name, method.getDeclaringClass().getName())) : new MethodInvoker(method);
1✔
161
    getMethods.put(name, invoker);
1✔
162
    Type returnType = TypeParameterResolver.resolveReturnType(method, type);
1✔
163
    getTypes.put(name, Map.entry(returnType, typeToClass(returnType)));
1✔
164
  }
1✔
165

166
  private void addSetMethods(Method[] methods) {
167
    Map<String, List<Method>> conflictingSetters = new HashMap<>();
1✔
168
    Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 1 && PropertyNamer.isSetter(m.getName()))
1✔
169
        .forEach(m -> addMethodConflict(conflictingSetters, PropertyNamer.methodToProperty(m.getName()), m));
1✔
170
    resolveSetterConflicts(conflictingSetters);
1✔
171
  }
1✔
172

173
  private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
174
    if (isValidPropertyName(name)) {
1!
175
      List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
1✔
176
      list.add(method);
1✔
177
    }
178
  }
1✔
179

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

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

227
  private void addSetMethod(String name, Method method) {
228
    MethodInvoker invoker = new MethodInvoker(method);
1✔
229
    setMethods.put(name, invoker);
1✔
230
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
1✔
231
    setTypes.put(name, Map.entry(paramTypes[0], typeToClass(paramTypes[0])));
1✔
232
  }
1✔
233

234
  private Class<?> typeToClass(Type src) {
235
    if (src instanceof Class) {
1✔
236
      return (Class<?>) src;
1✔
237
    } else if (src instanceof ParameterizedType) {
1✔
238
      return (Class<?>) ((ParameterizedType) src).getRawType();
1✔
239
    } else if (src instanceof GenericArrayType) {
1!
240
      Type componentType = ((GenericArrayType) src).getGenericComponentType();
1✔
241
      if (componentType instanceof Class) {
1!
242
        return Array.newInstance((Class<?>) componentType, 0).getClass();
×
243
      } else {
244
        Class<?> componentClass = typeToClass(componentType);
1✔
245
        return Array.newInstance(componentClass, 0).getClass();
1✔
246
      }
247
    }
248
    return Object.class;
×
249
  }
250

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

272
  private void addSetField(Field field) {
273
    if (isValidPropertyName(field.getName())) {
1!
274
      setMethods.put(field.getName(), new SetFieldInvoker(field));
1✔
275
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
276
      setTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
1✔
277
    }
278
  }
1✔
279

280
  private void addGetField(Field field) {
281
    if (isValidPropertyName(field.getName())) {
1✔
282
      getMethods.put(field.getName(), new GetFieldInvoker(field));
1✔
283
      Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
1✔
284
      getTypes.put(field.getName(), Map.entry(fieldType, typeToClass(fieldType)));
1✔
285
    }
286
  }
1✔
287

288
  private boolean isValidPropertyName(String name) {
289
    return !name.startsWith("$") && !"serialVersionUID".equals(name) && !"class".equals(name);
1!
290
  }
291

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

307
      // we also need to look for interface methods -
308
      // because the class may be abstract
309
      Class<?>[] interfaces = currentClass.getInterfaces();
1✔
310
      for (Class<?> anInterface : interfaces) {
1✔
311
        addUniqueMethods(uniqueMethods, anInterface.getMethods());
1✔
312
      }
313

314
      currentClass = currentClass.getSuperclass();
1✔
315
    }
1✔
316

317
    Collection<Method> methods = uniqueMethods.values();
1✔
318

319
    return methods.toArray(new Method[0]);
1✔
320
  }
321

322
  private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
323
    for (Method currentMethod : methods) {
1✔
324
      if (!currentMethod.isBridge()) {
1✔
325
        String signature = getSignature(currentMethod);
1✔
326
        // check to see if the method is already known
327
        // if it is known, then an extended class must have
328
        // overridden a method
329
        if (!uniqueMethods.containsKey(signature)) {
1✔
330
          uniqueMethods.put(signature, currentMethod);
1✔
331
        }
332
      }
333
    }
334
  }
1✔
335

336
  private String getSignature(Method method) {
337
    StringBuilder sb = new StringBuilder();
1✔
338
    Class<?> returnType = method.getReturnType();
1✔
339
    sb.append(returnType.getName()).append('#');
1✔
340
    sb.append(method.getName());
1✔
341
    Class<?>[] parameters = method.getParameterTypes();
1✔
342
    for (int i = 0; i < parameters.length; i++) {
1✔
343
      sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
1✔
344
    }
345
    return sb.toString();
1✔
346
  }
347

348
  /**
349
   * Checks whether can control member accessible.
350
   *
351
   * @return If can control member accessible, it return {@literal true}
352
   *
353
   * @since 3.5.0
354
   */
355
  public static boolean canControlMemberAccessible() {
356
    try {
357
      SecurityManager securityManager = System.getSecurityManager();
1✔
358
      if (null != securityManager) {
1!
359
        securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
×
360
      }
361
    } catch (SecurityException e) {
×
362
      return false;
×
363
    }
1✔
364
    return true;
1✔
365
  }
366

367
  /**
368
   * Gets the name of the class the instance provides information for.
369
   *
370
   * @return The class name
371
   */
372
  public Class<?> getType() {
373
    return clazz;
×
374
  }
375

376
  public Constructor<?> getDefaultConstructor() {
377
    if (defaultConstructor != null) {
×
378
      return defaultConstructor;
×
379
    }
380
    throw new ReflectionException("There is no default constructor for " + clazz);
×
381
  }
382

383
  public boolean hasDefaultConstructor() {
384
    return defaultConstructor != null;
1✔
385
  }
386

387
  public Invoker getSetInvoker(String propertyName) {
388
    Invoker method = setMethods.get(propertyName);
1✔
389
    if (method == null) {
1!
390
      throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + clazz + "'");
×
391
    }
392
    return method;
1✔
393
  }
394

395
  public Invoker getGetInvoker(String propertyName) {
396
    Invoker method = getMethods.get(propertyName);
1✔
397
    if (method == null) {
1✔
398
      throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + clazz + "'");
1✔
399
    }
400
    return method;
1✔
401
  }
402

403
  /**
404
   * Gets the type for a property setter.
405
   *
406
   * @param propertyName
407
   *          - the name of the property
408
   *
409
   * @return The Class of the property setter
410
   */
411
  public Class<?> getSetterType(String propertyName) {
412
    Class<?> clazz = setTypes.get(propertyName).getValue();
1✔
413
    if (clazz == null) {
1!
414
      throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + clazz + "'");
×
415
    }
416
    return clazz;
1✔
417
  }
418

419
  public Entry<Type, Class<?>> getGenericSetterType(String propertyName) {
420
    return setTypes.computeIfAbsent(propertyName, k -> {
1✔
421
      throw new ReflectionException("There is no setter for property named '" + k + "' in '" + clazz + "'");
1✔
422
    });
423
  }
424

425
  /**
426
   * Gets the type for a property getter.
427
   *
428
   * @param propertyName
429
   *          - the name of the property
430
   *
431
   * @return The Class of the property getter
432
   */
433
  public Class<?> getGetterType(String propertyName) {
434
    Class<?> clazz = getTypes.getOrDefault(propertyName, nullEntry).getValue();
1✔
435
    if (clazz == null) {
1!
436
      throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + clazz + "'");
×
437
    }
438
    return clazz;
1✔
439
  }
440

441
  public Entry<Type, Class<?>> getGenericGetterType(String propertyName) {
442
    return getTypes.computeIfAbsent(propertyName, k -> {
1✔
443
      throw new ReflectionException("There is no getter for property named '" + k + "' in '" + clazz + "'");
1✔
444
    });
445
  }
446

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

456
  /**
457
   * Gets an array of the writable properties for an object.
458
   *
459
   * @return The array
460
   */
461
  public String[] getSetablePropertyNames() {
462
    return writablePropertyNames;
1✔
463
  }
464

465
  /**
466
   * Check to see if a class has a writable property by name.
467
   *
468
   * @param propertyName
469
   *          - the name of the property to check
470
   *
471
   * @return True if the object has a writable property by the name
472
   */
473
  public boolean hasSetter(String propertyName) {
474
    return setMethods.containsKey(propertyName);
1✔
475
  }
476

477
  /**
478
   * Check to see if a class has a readable property by name.
479
   *
480
   * @param propertyName
481
   *          - the name of the property to check
482
   *
483
   * @return True if the object has a readable property by the name
484
   */
485
  public boolean hasGetter(String propertyName) {
486
    return getMethods.containsKey(propertyName);
1✔
487
  }
488

489
  public String findPropertyName(String name) {
490
    return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
1✔
491
  }
492

493
  /**
494
   * Class.isRecord() alternative for Java 15 and older.
495
   */
496
  private static boolean isRecord(Class<?> clazz) {
497
    try {
498
      return isRecordMethodHandle != null && (boolean) isRecordMethodHandle.invokeExact(clazz);
1!
499
    } catch (Throwable e) {
×
500
      throw new ReflectionException("Failed to invoke 'Class.isRecord()'.", e);
×
501
    }
502
  }
503

504
  private static MethodHandle getIsRecordMethodHandle() {
505
    MethodHandles.Lookup lookup = MethodHandles.lookup();
1✔
506
    MethodType mt = MethodType.methodType(boolean.class);
1✔
507
    try {
508
      return lookup.findVirtual(Class.class, "isRecord", mt);
1✔
509
    } catch (NoSuchMethodException | IllegalAccessException e) {
×
510
      return null;
×
511
    }
512
  }
513
}
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

© 2026 Coveralls, Inc