View Javadoc
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.reflect.Array;
19  import java.lang.reflect.Field;
20  import java.lang.reflect.GenericArrayType;
21  import java.lang.reflect.Method;
22  import java.lang.reflect.ParameterizedType;
23  import java.lang.reflect.Type;
24  import java.lang.reflect.TypeVariable;
25  import java.lang.reflect.WildcardType;
26  import java.util.Arrays;
27  import java.util.Objects;
28  
29  /**
30   * @author Iwao AVE!
31   * @author Vladimir Sitnikov
32   */
33  public class TypeParameterResolver {
34  
35    public static Type[] resolveClassTypeParams(Class<?> classWithTypeParams, Class<?> childClass) {
36      TypeVariable<?>[] typeArgs = classWithTypeParams.getTypeParameters();
37      Type[] result = new Type[typeArgs.length];
38      for (int i = 0; i < typeArgs.length; i++) {
39        result[i] = resolveTypeVar(typeArgs[i], childClass, classWithTypeParams);
40      }
41      return result;
42    }
43  
44    /**
45     * Resolve field type.
46     *
47     * @param field
48     *          the field
49     * @param srcType
50     *          the src type
51     *
52     * @return The field type as {@link Type}. If it has type parameters in the declaration,<br>
53     *         they will be resolved to the actual runtime {@link Type}s.
54     */
55    public static Type resolveFieldType(Field field, Type srcType) {
56      Type fieldType = field.getGenericType();
57      Class<?> declaringClass = field.getDeclaringClass();
58      return resolveType(fieldType, srcType, declaringClass);
59    }
60  
61    /**
62     * Resolve return type.
63     *
64     * @param method
65     *          the method
66     * @param srcType
67     *          the src type
68     *
69     * @return The return type of the method as {@link Type}. If it has type parameters in the declaration,<br>
70     *         they will be resolved to the actual runtime {@link Type}s.
71     */
72    public static Type resolveReturnType(Method method, Type srcType) {
73      Type returnType = method.getGenericReturnType();
74      Class<?> declaringClass = method.getDeclaringClass();
75      return resolveType(returnType, srcType, declaringClass);
76    }
77  
78    /**
79     * Resolve param types.
80     *
81     * @param method
82     *          the method
83     * @param srcType
84     *          the src type
85     *
86     * @return The parameter types of the method as an array of {@link Type}s. If they have type parameters in the
87     *         declaration,<br>
88     *         they will be resolved to the actual runtime {@link Type}s.
89     */
90    public static Type[] resolveParamTypes(Method method, Type srcType) {
91      Type[] paramTypes = method.getGenericParameterTypes();
92      Class<?> declaringClass = method.getDeclaringClass();
93      return resolveTypes(paramTypes, srcType, declaringClass);
94    }
95  
96    private static Type[] resolveTypes(Type[] types, Type srcType, Class<?> declaringClass) {
97      Type[] args = new Type[types.length];
98      for (int i = 0; i < types.length; i++) {
99        args[i] = resolveType(types[i], srcType, declaringClass);
100     }
101     return args;
102   }
103 
104   private static Type resolveType(Type type, Type srcType, Class<?> declaringClass) {
105     if (type instanceof TypeVariable) {
106       return resolveTypeVar((TypeVariable<?>) type, srcType, declaringClass);
107     } else if (type instanceof ParameterizedType) {
108       return resolveParameterizedType((ParameterizedType) type, srcType, declaringClass);
109     } else if (type instanceof GenericArrayType) {
110       return resolveGenericArrayType((GenericArrayType) type, srcType, declaringClass);
111     } else if (type instanceof WildcardType) {
112       return resolveWildcardType((WildcardType) type, srcType, declaringClass);
113     } else {
114       return type;
115     }
116   }
117 
118   private static Type resolveGenericArrayType(GenericArrayType genericArrayType, Type srcType,
119       Class<?> declaringClass) {
120     Type componentType = genericArrayType.getGenericComponentType();
121     Type resolvedComponentType = resolveType(componentType, srcType, declaringClass);
122     if (resolvedComponentType instanceof Class) {
123       return Array.newInstance((Class<?>) resolvedComponentType, 0).getClass();
124     } else {
125       return new GenericArrayTypeImpl(resolvedComponentType);
126     }
127   }
128 
129   private static ParameterizedType resolveParameterizedType(ParameterizedType parameterizedType, Type srcType,
130       Class<?> declaringClass) {
131     Class<?> rawType = (Class<?>) parameterizedType.getRawType();
132     Type ownerType = parameterizedType.getOwnerType();
133     Type[] typeArgs = parameterizedType.getActualTypeArguments();
134     Type[] args = resolveTypes(typeArgs, srcType, declaringClass);
135     return new ParameterizedTypeImpl(rawType, ownerType, args);
136   }
137 
138   private static Type resolveWildcardType(WildcardType wildcardType, Type srcType, Class<?> declaringClass) {
139     Type[] lowerBounds = resolveTypes(wildcardType.getLowerBounds(), srcType, declaringClass);
140     Type[] upperBounds = resolveTypes(wildcardType.getUpperBounds(), srcType, declaringClass);
141     return new WildcardTypeImpl(lowerBounds, upperBounds);
142   }
143 
144   private static Type resolveTypeVar(TypeVariable<?> typeVar, Type srcType, Class<?> declaringClass) {
145     Type result;
146     Class<?> clazz;
147     if (srcType instanceof Class) {
148       clazz = (Class<?>) srcType;
149     } else if (srcType instanceof ParameterizedType) {
150       ParameterizedType parameterizedType = (ParameterizedType) srcType;
151       clazz = (Class<?>) parameterizedType.getRawType();
152       if (clazz == declaringClass) {
153         TypeVariable<?>[] typeVars = declaringClass.getTypeParameters();
154         for (int i = 0; i < typeVars.length; i++) {
155           if (typeVar.equals(typeVars[i])) {
156             return parameterizedType.getActualTypeArguments()[i];
157           }
158         }
159       }
160     } else {
161       throw new IllegalArgumentException(
162           "The 2nd arg must be Class or ParameterizedType, but was: " + srcType.getClass());
163     }
164 
165     if (clazz == declaringClass) {
166       Type[] bounds = typeVar.getBounds();
167       if (bounds.length > 0) {
168         return bounds[0];
169       }
170       return Object.class;
171     }
172 
173     Type superclass = clazz.getGenericSuperclass();
174     result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superclass);
175     if (result != null) {
176       return result;
177     }
178 
179     Type[] superInterfaces = clazz.getGenericInterfaces();
180     for (Type superInterface : superInterfaces) {
181       result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superInterface);
182       if (result != null) {
183         return result;
184       }
185     }
186     return Object.class;
187   }
188 
189   private static Type scanSuperTypes(TypeVariable<?> typeVar, Type srcType, Class<?> declaringClass, Class<?> clazz,
190       Type superclass) {
191     if (superclass instanceof ParameterizedType) {
192       ParameterizedType parentAsType = (ParameterizedType) superclass;
193       Class<?> parentAsClass = (Class<?>) parentAsType.getRawType();
194       TypeVariable<?>[] parentTypeVars = parentAsClass.getTypeParameters();
195       if (srcType instanceof ParameterizedType) {
196         parentAsType = translateParentTypeVars((ParameterizedType) srcType, clazz, parentAsType);
197       }
198       if (declaringClass == parentAsClass) {
199         for (int i = 0; i < parentTypeVars.length; i++) {
200           if (typeVar.equals(parentTypeVars[i])) {
201             Type actualType = parentAsType.getActualTypeArguments()[i];
202             return actualType instanceof TypeVariable<?> ? Object.class : actualType;
203           }
204         }
205       }
206       if (declaringClass.isAssignableFrom(parentAsClass)) {
207         return resolveTypeVar(typeVar, parentAsType, declaringClass);
208       }
209     } else if (superclass instanceof Class && declaringClass.isAssignableFrom((Class<?>) superclass)) {
210       return resolveTypeVar(typeVar, superclass, declaringClass);
211     }
212     return null;
213   }
214 
215   private static ParameterizedType translateParentTypeVars(ParameterizedType srcType, Class<?> srcClass,
216       ParameterizedType parentType) {
217     Type[] parentTypeArgs = parentType.getActualTypeArguments();
218     Type[] srcTypeArgs = srcType.getActualTypeArguments();
219     TypeVariable<?>[] srcTypeVars = srcClass.getTypeParameters();
220     Type[] newParentArgs = new Type[parentTypeArgs.length];
221     boolean noChange = true;
222     for (int i = 0; i < parentTypeArgs.length; i++) {
223       if (parentTypeArgs[i] instanceof TypeVariable) {
224         for (int j = 0; j < srcTypeVars.length; j++) {
225           if (srcTypeVars[j].equals(parentTypeArgs[i])) {
226             noChange = false;
227             newParentArgs[i] = srcTypeArgs[j];
228           }
229         }
230       } else {
231         newParentArgs[i] = parentTypeArgs[i];
232       }
233     }
234     return noChange ? parentType
235         : new ParameterizedTypeImpl((Class<?>) parentType.getRawType(), parentType.getOwnerType(), newParentArgs);
236   }
237 
238   private TypeParameterResolver() {
239     super();
240   }
241 
242   static class ParameterizedTypeImpl implements ParameterizedType {
243     private final Class<?> rawType;
244 
245     private final Type ownerType;
246 
247     private final Type[] actualTypeArguments;
248 
249     ParameterizedTypeImpl(Class<?> rawType, Type ownerType, Type[] actualTypeArguments) {
250       super();
251       this.rawType = rawType;
252       this.ownerType = ownerType;
253       this.actualTypeArguments = actualTypeArguments;
254     }
255 
256     @Override
257     public Type[] getActualTypeArguments() {
258       return actualTypeArguments;
259     }
260 
261     @Override
262     public Type getOwnerType() {
263       return ownerType;
264     }
265 
266     @Override
267     public Type getRawType() {
268       return rawType;
269     }
270 
271     @Override
272     public int hashCode() {
273       return (ownerType == null ? 0 : ownerType.hashCode()) ^ Arrays.hashCode(actualTypeArguments) ^ rawType.hashCode();
274     }
275 
276     @Override
277     public boolean equals(Object obj) {
278       if (!(obj instanceof ParameterizedType)) {
279         return false;
280       }
281       ParameterizedType other = (ParameterizedType) obj;
282       return rawType.equals(other.getRawType()) && Objects.equals(ownerType, other.getOwnerType())
283           && Arrays.equals(actualTypeArguments, other.getActualTypeArguments());
284     }
285 
286     @Override
287     public String toString() {
288       StringBuilder s = new StringBuilder();
289       if (ownerType != null) {
290         s.append(ownerType.getTypeName()).append("$");
291         s.append(rawType.getSimpleName());
292       } else {
293         s.append(rawType.getName());
294       }
295       int argLength = actualTypeArguments.length;
296       if (argLength > 0) {
297         s.append("<");
298         for (int i = 0; i < argLength; i++) {
299           if (i > 0) {
300             s.append(", ");
301           }
302           s.append(actualTypeArguments[i].getTypeName());
303         }
304         s.append(">");
305       }
306       return s.toString();
307     }
308   }
309 
310   static class WildcardTypeImpl implements WildcardType {
311     private final Type[] lowerBounds;
312 
313     private final Type[] upperBounds;
314 
315     WildcardTypeImpl(Type[] lowerBounds, Type[] upperBounds) {
316       super();
317       this.lowerBounds = lowerBounds;
318       this.upperBounds = upperBounds;
319     }
320 
321     @Override
322     public Type[] getLowerBounds() {
323       return lowerBounds;
324     }
325 
326     @Override
327     public Type[] getUpperBounds() {
328       return upperBounds;
329     }
330 
331     @Override
332     public int hashCode() {
333       final int prime = 31;
334       int result = 1;
335       result = prime * result + Arrays.hashCode(lowerBounds);
336       result = prime * result + Arrays.hashCode(upperBounds);
337       return result;
338     }
339 
340     @Override
341     public boolean equals(Object obj) {
342       if (this == obj) {
343         return true;
344       }
345       if (!(obj instanceof WildcardType)) {
346         return false;
347       }
348       WildcardType other = (WildcardType) obj;
349       return Arrays.equals(lowerBounds, other.getLowerBounds()) && Arrays.equals(upperBounds, other.getUpperBounds());
350     }
351 
352     @Override
353     public String toString() {
354       StringBuilder s = new StringBuilder().append("?");
355       if (lowerBounds.length > 0) {
356         s.append(" super ").append(lowerBounds[0].getTypeName());
357       } else if (upperBounds.length > 0 && upperBounds[0] != Object.class) {
358         s.append(" extends ").append(upperBounds[0].getTypeName());
359       }
360       return s.toString();
361     }
362   }
363 
364   static class GenericArrayTypeImpl implements GenericArrayType {
365     private final Type genericComponentType;
366 
367     GenericArrayTypeImpl(Type genericComponentType) {
368       super();
369       this.genericComponentType = genericComponentType;
370     }
371 
372     @Override
373     public Type getGenericComponentType() {
374       return genericComponentType;
375     }
376 
377     @Override
378     public int hashCode() {
379       return Objects.hash(genericComponentType);
380     }
381 
382     @Override
383     public boolean equals(Object obj) {
384       if (this == obj) {
385         return true;
386       }
387       if (!(obj instanceof GenericArrayType)) {
388         return false;
389       }
390       GenericArrayType other = (GenericArrayType) obj;
391       return Objects.equals(genericComponentType, other.getGenericComponentType());
392     }
393 
394     @Override
395     public String toString() {
396       return new StringBuilder().append(genericComponentType.getTypeName()).append("[]").toString();
397     }
398   }
399 }