Reflector.java

  1. /*
  2.  *    Copyright 2009-2022 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.  *       http://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
  47.  * allows for easy mapping between property 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 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)
  89.       .findAny().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.           } else if (candidate.getName().startsWith("is")) {
  114.             winner = candidate;
  115.           }
  116.         } else if (candidateType.isAssignableFrom(winnerType)) {
  117.           // OK getter type is descendant
  118.         } else if (winnerType.isAssignableFrom(candidateType)) {
  119.           winner = candidate;
  120.         } else {
  121.           isAmbiguous = true;
  122.           break;
  123.         }
  124.       }
  125.       addGetMethod(propName, winner, isAmbiguous);
  126.     }
  127.   }

  128.   private void addGetMethod(String name, Method method, boolean isAmbiguous) {
  129.     MethodInvoker invoker = isAmbiguous
  130.         ? 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()))
  133.         : new MethodInvoker(method);
  134.     getMethods.put(name, invoker);
  135.     Type returnType = TypeParameterResolver.resolveReturnType(method, type);
  136.     getTypes.put(name, typeToClass(returnType));
  137.   }

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

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

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

  174.   private Method pickBetterSetter(Method setter1, Method setter2, String property) {
  175.     if (setter1 == null) {
  176.       return setter2;
  177.     }
  178.     Class<?> paramType1 = setter1.getParameterTypes()[0];
  179.     Class<?> paramType2 = setter2.getParameterTypes()[0];
  180.     if (paramType1.isAssignableFrom(paramType2)) {
  181.       return setter2;
  182.     } else 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}''.",
  188.             property, 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
  259.    * declared in this class and any superclass.
  260.    * We use this method, instead of the simpler <code>Class.getMethods()</code>,
  261.    * because we want to look for private methods as well.
  262.    *
  263.    * @param clazz The class
  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.     if (returnType != null) {
  299.       sb.append(returnType.getName()).append('#');
  300.     }
  301.     sb.append(method.getName());
  302.     Class<?>[] parameters = method.getParameterTypes();
  303.     for (int i = 0; i < parameters.length; i++) {
  304.       sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
  305.     }
  306.     return sb.toString();
  307.   }

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

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

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

  340.   public boolean hasDefaultConstructor() {
  341.     return defaultConstructor != null;
  342.   }

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

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

  357.   /**
  358.    * Gets the type for a property setter.
  359.    *
  360.    * @param propertyName - the name of the property
  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 - the name of the property
  374.    * @return The Class of the property getter
  375.    */
  376.   public Class<?> getGetterType(String propertyName) {
  377.     Class<?> clazz = getTypes.get(propertyName);
  378.     if (clazz == null) {
  379.       throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  380.     }
  381.     return clazz;
  382.   }

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

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

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

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

  417.   public String findPropertyName(String name) {
  418.     return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
  419.   }

  420.   /**
  421.    * Class.isRecord() alternative for Java 15 and older.
  422.    */
  423.   private static boolean isRecord(Class<?> clazz) {
  424.     try {
  425.       return isRecordMethodHandle != null && (boolean)isRecordMethodHandle.invokeExact(clazz);
  426.     } catch (Throwable e) {
  427.       throw new ReflectionException("Failed to invoke 'Class.isRecord()'.", e);
  428.     }
  429.   }

  430.   private static MethodHandle getIsRecordMethodHandle() {
  431.     MethodHandles.Lookup lookup = MethodHandles.lookup();
  432.     MethodType mt = MethodType.methodType(boolean.class);
  433.     try {
  434.       return lookup.findVirtual(Class.class, "isRecord", mt);
  435.     } catch (NoSuchMethodException | IllegalAccessException e) {
  436.       return null;
  437.     }
  438.   }
  439. }