Reflector.java

  1. /*
  2.  *    Copyright 2009-2024 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. import java.lang.invoke.MethodHandle;
  18. import java.lang.invoke.MethodHandles;
  19. import java.lang.invoke.MethodType;
  20. import java.lang.reflect.Array;
  21. import java.lang.reflect.Constructor;
  22. import java.lang.reflect.Field;
  23. import java.lang.reflect.GenericArrayType;
  24. import java.lang.reflect.Method;
  25. import java.lang.reflect.Modifier;
  26. import java.lang.reflect.ParameterizedType;
  27. import java.lang.reflect.ReflectPermission;
  28. import java.lang.reflect.Type;
  29. import java.text.MessageFormat;
  30. import java.util.ArrayList;
  31. import java.util.Arrays;
  32. import java.util.Collection;
  33. import java.util.HashMap;
  34. import java.util.List;
  35. import java.util.Locale;
  36. import java.util.Map;
  37. import java.util.Map.Entry;

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

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

  52.   private static final MethodHandle isRecordMethodHandle = getIsRecordMethodHandle();
  53.   private final Class<?> type;
  54.   private final String[] readablePropertyNames;
  55.   private final String[] writablePropertyNames;
  56.   private final Map<String, Invoker> setMethods = new HashMap<>();
  57.   private final Map<String, Invoker> getMethods = new HashMap<>();
  58.   private final Map<String, Class<?>> setTypes = new HashMap<>();
  59.   private final Map<String, Class<?>> getTypes = new HashMap<>();
  60.   private Constructor<?> defaultConstructor;

  61.   private final Map<String, String> caseInsensitivePropertyMap = new HashMap<>();

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

  82.   private void addRecordGetMethods(Method[] methods) {
  83.     Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0)
  84.         .forEach(m -> addGetMethod(m.getName(), m, false));
  85.   }

  86.   private void addDefaultConstructor(Class<?> clazz) {
  87.     Constructor<?>[] constructors = clazz.getDeclaredConstructors();
  88.     Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0).findAny()
  89.         .ifPresent(constructor -> this.defaultConstructor = constructor);
  90.   }

  91.   private void addGetMethods(Method[] methods) {
  92.     Map<String, List<Method>> conflictingGetters = new HashMap<>();
  93.     Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
  94.         .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
  95.     resolveGetterConflicts(conflictingGetters);
  96.   }

  97.   private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
  98.     for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
  99.       Method winner = null;
  100.       String propName = entry.getKey();
  101.       boolean isAmbiguous = false;
  102.       for (Method candidate : entry.getValue()) {
  103.         if (winner == null) {
  104.           winner = candidate;
  105.           continue;
  106.         }
  107.         Class<?> winnerType = winner.getReturnType();
  108.         Class<?> candidateType = candidate.getReturnType();
  109.         if (candidateType.equals(winnerType)) {
  110.           if (!boolean.class.equals(candidateType)) {
  111.             isAmbiguous = true;
  112.             break;
  113.           }
  114.           if (candidate.getName().startsWith("is")) {
  115.             winner = candidate;
  116.           }
  117.         } else if (candidateType.isAssignableFrom(winnerType)) {
  118.           // OK getter type is descendant
  119.         } else if (winnerType.isAssignableFrom(candidateType)) {
  120.           winner = candidate;
  121.         } else {
  122.           isAmbiguous = true;
  123.           break;
  124.         }
  125.       }
  126.       addGetMethod(propName, winner, isAmbiguous);
  127.     }
  128.   }

  129.   private void addGetMethod(String name, Method method, boolean isAmbiguous) {
  130.     MethodInvoker invoker = isAmbiguous ? new AmbiguousMethodInvoker(method, MessageFormat.format(
  131.         "Illegal overloaded getter method with ambiguous type for property ''{0}'' in class ''{1}''. This breaks the JavaBeans specification and can cause unpredictable results.",
  132.         name, method.getDeclaringClass().getName())) : new MethodInvoker(method);
  133.     getMethods.put(name, invoker);
  134.     Type returnType = TypeParameterResolver.resolveReturnType(method, type);
  135.     getTypes.put(name, typeToClass(returnType));
  136.   }

  137.   private void addSetMethods(Method[] methods) {
  138.     Map<String, List<Method>> conflictingSetters = new HashMap<>();
  139.     Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 1 && PropertyNamer.isSetter(m.getName()))
  140.         .forEach(m -> addMethodConflict(conflictingSetters, PropertyNamer.methodToProperty(m.getName()), m));
  141.     resolveSetterConflicts(conflictingSetters);
  142.   }

  143.   private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
  144.     if (isValidPropertyName(name)) {
  145.       List<Method> list = MapUtil.computeIfAbsent(conflictingMethods, name, k -> new ArrayList<>());
  146.       list.add(method);
  147.     }
  148.   }

  149.   private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
  150.     for (Entry<String, List<Method>> entry : conflictingSetters.entrySet()) {
  151.       String propName = entry.getKey();
  152.       List<Method> setters = entry.getValue();
  153.       Class<?> getterType = getTypes.get(propName);
  154.       boolean isGetterAmbiguous = getMethods.get(propName) instanceof AmbiguousMethodInvoker;
  155.       boolean isSetterAmbiguous = false;
  156.       Method match = null;
  157.       for (Method setter : setters) {
  158.         if (!isGetterAmbiguous && setter.getParameterTypes()[0].equals(getterType)) {
  159.           // should be the best match
  160.           match = setter;
  161.           break;
  162.         }
  163.         if (!isSetterAmbiguous) {
  164.           match = pickBetterSetter(match, setter, propName);
  165.           isSetterAmbiguous = match == null;
  166.         }
  167.       }
  168.       if (match != null) {
  169.         addSetMethod(propName, match);
  170.       }
  171.     }
  172.   }

  173.   private Method pickBetterSetter(Method setter1, Method setter2, String property) {
  174.     if (setter1 == null) {
  175.       return setter2;
  176.     }
  177.     Class<?> paramType1 = setter1.getParameterTypes()[0];
  178.     Class<?> paramType2 = setter2.getParameterTypes()[0];
  179.     if (paramType1.isAssignableFrom(paramType2)) {
  180.       return setter2;
  181.     }
  182.     if (paramType2.isAssignableFrom(paramType1)) {
  183.       return setter1;
  184.     }
  185.     MethodInvoker invoker = new AmbiguousMethodInvoker(setter1,
  186.         MessageFormat.format(
  187.             "Ambiguous setters defined for property ''{0}'' in class ''{1}'' with types ''{2}'' and ''{3}''.", property,
  188.             setter2.getDeclaringClass().getName(), paramType1.getName(), paramType2.getName()));
  189.     setMethods.put(property, invoker);
  190.     Type[] paramTypes = TypeParameterResolver.resolveParamTypes(setter1, type);
  191.     setTypes.put(property, typeToClass(paramTypes[0]));
  192.     return null;
  193.   }

  194.   private void addSetMethod(String name, Method method) {
  195.     MethodInvoker invoker = new MethodInvoker(method);
  196.     setMethods.put(name, invoker);
  197.     Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
  198.     setTypes.put(name, typeToClass(paramTypes[0]));
  199.   }

  200.   private Class<?> typeToClass(Type src) {
  201.     Class<?> result = null;
  202.     if (src instanceof Class) {
  203.       result = (Class<?>) src;
  204.     } else if (src instanceof ParameterizedType) {
  205.       result = (Class<?>) ((ParameterizedType) src).getRawType();
  206.     } else if (src instanceof GenericArrayType) {
  207.       Type componentType = ((GenericArrayType) src).getGenericComponentType();
  208.       if (componentType instanceof Class) {
  209.         result = Array.newInstance((Class<?>) componentType, 0).getClass();
  210.       } else {
  211.         Class<?> componentClass = typeToClass(componentType);
  212.         result = Array.newInstance(componentClass, 0).getClass();
  213.       }
  214.     }
  215.     if (result == null) {
  216.       result = Object.class;
  217.     }
  218.     return result;
  219.   }

  220.   private void addFields(Class<?> clazz) {
  221.     Field[] fields = clazz.getDeclaredFields();
  222.     for (Field field : fields) {
  223.       if (!setMethods.containsKey(field.getName())) {
  224.         // issue #379 - removed the check for final because JDK 1.5 allows
  225.         // modification of final fields through reflection (JSR-133). (JGB)
  226.         // pr #16 - final static can only be set by the classloader
  227.         int modifiers = field.getModifiers();
  228.         if (!Modifier.isFinal(modifiers) || !Modifier.isStatic(modifiers)) {
  229.           addSetField(field);
  230.         }
  231.       }
  232.       if (!getMethods.containsKey(field.getName())) {
  233.         addGetField(field);
  234.       }
  235.     }
  236.     if (clazz.getSuperclass() != null) {
  237.       addFields(clazz.getSuperclass());
  238.     }
  239.   }

  240.   private void addSetField(Field field) {
  241.     if (isValidPropertyName(field.getName())) {
  242.       setMethods.put(field.getName(), new SetFieldInvoker(field));
  243.       Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
  244.       setTypes.put(field.getName(), typeToClass(fieldType));
  245.     }
  246.   }

  247.   private void addGetField(Field field) {
  248.     if (isValidPropertyName(field.getName())) {
  249.       getMethods.put(field.getName(), new GetFieldInvoker(field));
  250.       Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
  251.       getTypes.put(field.getName(), typeToClass(fieldType));
  252.     }
  253.   }

  254.   private boolean isValidPropertyName(String name) {
  255.     return !name.startsWith("$") && !"serialVersionUID".equals(name) && !"class".equals(name);
  256.   }

  257.   /**
  258.    * This method returns an array containing all methods declared in this class and any superclass. We use this method,
  259.    * instead of the simpler <code>Class.getMethods()</code>, because we want to look for private methods as well.
  260.    *
  261.    * @param clazz
  262.    *          The class
  263.    *
  264.    * @return An array containing all methods in this class
  265.    */
  266.   private Method[] getClassMethods(Class<?> clazz) {
  267.     Map<String, Method> uniqueMethods = new HashMap<>();
  268.     Class<?> currentClass = clazz;
  269.     while (currentClass != null && currentClass != Object.class) {
  270.       addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());

  271.       // we also need to look for interface methods -
  272.       // because the class may be abstract
  273.       Class<?>[] interfaces = currentClass.getInterfaces();
  274.       for (Class<?> anInterface : interfaces) {
  275.         addUniqueMethods(uniqueMethods, anInterface.getMethods());
  276.       }

  277.       currentClass = currentClass.getSuperclass();
  278.     }

  279.     Collection<Method> methods = uniqueMethods.values();

  280.     return methods.toArray(new Method[0]);
  281.   }

  282.   private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
  283.     for (Method currentMethod : methods) {
  284.       if (!currentMethod.isBridge()) {
  285.         String signature = getSignature(currentMethod);
  286.         // check to see if the method is already known
  287.         // if it is known, then an extended class must have
  288.         // overridden a method
  289.         if (!uniqueMethods.containsKey(signature)) {
  290.           uniqueMethods.put(signature, currentMethod);
  291.         }
  292.       }
  293.     }
  294.   }

  295.   private String getSignature(Method method) {
  296.     StringBuilder sb = new StringBuilder();
  297.     Class<?> returnType = method.getReturnType();
  298.     sb.append(returnType.getName()).append('#');
  299.     sb.append(method.getName());
  300.     Class<?>[] parameters = method.getParameterTypes();
  301.     for (int i = 0; i < parameters.length; i++) {
  302.       sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
  303.     }
  304.     return sb.toString();
  305.   }

  306.   /**
  307.    * Checks whether can control member accessible.
  308.    *
  309.    * @return If can control member accessible, it return {@literal true}
  310.    *
  311.    * @since 3.5.0
  312.    */
  313.   public static boolean canControlMemberAccessible() {
  314.     try {
  315.       SecurityManager securityManager = System.getSecurityManager();
  316.       if (null != securityManager) {
  317.         securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
  318.       }
  319.     } catch (SecurityException e) {
  320.       return false;
  321.     }
  322.     return true;
  323.   }

  324.   /**
  325.    * Gets the name of the class the instance provides information for.
  326.    *
  327.    * @return The class name
  328.    */
  329.   public Class<?> getType() {
  330.     return type;
  331.   }

  332.   public Constructor<?> getDefaultConstructor() {
  333.     if (defaultConstructor != null) {
  334.       return defaultConstructor;
  335.     }
  336.     throw new ReflectionException("There is no default constructor for " + type);
  337.   }

  338.   public boolean hasDefaultConstructor() {
  339.     return defaultConstructor != null;
  340.   }

  341.   public Invoker getSetInvoker(String propertyName) {
  342.     Invoker method = setMethods.get(propertyName);
  343.     if (method == null) {
  344.       throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
  345.     }
  346.     return method;
  347.   }

  348.   public Invoker getGetInvoker(String propertyName) {
  349.     Invoker method = getMethods.get(propertyName);
  350.     if (method == null) {
  351.       throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  352.     }
  353.     return method;
  354.   }

  355.   /**
  356.    * Gets the type for a property setter.
  357.    *
  358.    * @param propertyName
  359.    *          - the name of the property
  360.    *
  361.    * @return The Class of the property setter
  362.    */
  363.   public Class<?> getSetterType(String propertyName) {
  364.     Class<?> clazz = setTypes.get(propertyName);
  365.     if (clazz == null) {
  366.       throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'");
  367.     }
  368.     return clazz;
  369.   }

  370.   /**
  371.    * Gets the type for a property getter.
  372.    *
  373.    * @param propertyName
  374.    *          - the name of the property
  375.    *
  376.    * @return The Class of the property getter
  377.    */
  378.   public Class<?> getGetterType(String propertyName) {
  379.     Class<?> clazz = getTypes.get(propertyName);
  380.     if (clazz == null) {
  381.       throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  382.     }
  383.     return clazz;
  384.   }

  385.   /**
  386.    * Gets an array of the readable properties for an object.
  387.    *
  388.    * @return The array
  389.    */
  390.   public String[] getGetablePropertyNames() {
  391.     return readablePropertyNames;
  392.   }

  393.   /**
  394.    * Gets an array of the writable properties for an object.
  395.    *
  396.    * @return The array
  397.    */
  398.   public String[] getSetablePropertyNames() {
  399.     return writablePropertyNames;
  400.   }

  401.   /**
  402.    * Check to see if a class has a writable property by name.
  403.    *
  404.    * @param propertyName
  405.    *          - the name of the property to check
  406.    *
  407.    * @return True if the object has a writable property by the name
  408.    */
  409.   public boolean hasSetter(String propertyName) {
  410.     return setMethods.containsKey(propertyName);
  411.   }

  412.   /**
  413.    * Check to see if a class has a readable property by name.
  414.    *
  415.    * @param propertyName
  416.    *          - the name of the property to check
  417.    *
  418.    * @return True if the object has a readable property by the name
  419.    */
  420.   public boolean hasGetter(String propertyName) {
  421.     return getMethods.containsKey(propertyName);
  422.   }

  423.   public String findPropertyName(String name) {
  424.     return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
  425.   }

  426.   /**
  427.    * Class.isRecord() alternative for Java 15 and older.
  428.    */
  429.   private static boolean isRecord(Class<?> clazz) {
  430.     try {
  431.       return isRecordMethodHandle != null && (boolean) isRecordMethodHandle.invokeExact(clazz);
  432.     } catch (Throwable e) {
  433.       throw new ReflectionException("Failed to invoke 'Class.isRecord()'.", e);
  434.     }
  435.   }

  436.   private static MethodHandle getIsRecordMethodHandle() {
  437.     MethodHandles.Lookup lookup = MethodHandles.lookup();
  438.     MethodType mt = MethodType.methodType(boolean.class);
  439.     try {
  440.       return lookup.findVirtual(Class.class, "isRecord", mt);
  441.     } catch (NoSuchMethodException | IllegalAccessException e) {
  442.       return null;
  443.     }
  444.   }
  445. }