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

mybatis / mybatis-3 / 2743

12 Mar 2025 05:12AM UTC coverage: 87.256% (+0.02%) from 87.235%
2743

Pull #3427

github

web-flow
Merge e88ddb146 into 1a145cdff
Pull Request #3427: Rollback transactions only when an error occurs.

3683 of 4487 branches covered (82.08%)

2 of 2 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

9675 of 11088 relevant lines covered (87.26%)

0.87 hits per line

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

93.02
/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.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

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

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

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

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

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

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

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

106
  private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
107
    for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
1✔
108
      Method winner = null;
1✔
109
      String propName = entry.getKey();
1✔
110
      boolean isAmbiguous = false;
1✔
111
      for (Method candidate : entry.getValue()) {
1✔
112
        if (winner == null) {
1✔
113
          winner = candidate;
1✔
114
          continue;
1✔
115
        }
116
        Class<?> winnerType = winner.getReturnType();
1✔
117
        Class<?> candidateType = candidate.getReturnType();
1✔
118
        if (candidateType.equals(winnerType)) {
1✔
119
          if (!boolean.class.equals(candidateType)) {
1✔
120
            isAmbiguous = true;
1✔
121
            break;
1✔
122
          }
123
          if (candidate.getName().startsWith("is")) {
1!
UNCOV
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 = conflictingMethods.computeIfAbsent(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
    }
196
    if (paramType2.isAssignableFrom(paramType1)) {
1✔
197
      return setter1;
1✔
198
    }
199
    MethodInvoker invoker = new AmbiguousMethodInvoker(setter1,
1✔
200
        MessageFormat.format(
1✔
201
            "Ambiguous setters defined for property ''{0}'' in class ''{1}'' with types ''{2}'' and ''{3}''.", property,
202
            setter2.getDeclaringClass().getName(), paramType1.getName(), paramType2.getName()));
1✔
203
    setMethods.put(property, invoker);
1✔
204
    Type[] paramTypes = TypeParameterResolver.resolveParamTypes(setter1, type);
1✔
205
    setTypes.put(property, typeToClass(paramTypes[0]));
1✔
206
    return null;
1✔
207
  }
208

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

478
  private static MethodHandle getIsRecordMethodHandle() {
479
    MethodHandles.Lookup lookup = MethodHandles.lookup();
1✔
480
    MethodType mt = MethodType.methodType(boolean.class);
1✔
481
    try {
482
      return lookup.findVirtual(Class.class, "isRecord", mt);
1✔
483
    } catch (NoSuchMethodException | IllegalAccessException e) {
×
484
      return null;
×
485
    }
486
  }
487
}
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