|
4 | 4 |
|
5 | 5 | import java.lang.reflect.ParameterizedType; |
6 | 6 | import java.lang.reflect.Type; |
| 7 | +import java.lang.reflect.TypeVariable; |
7 | 8 |
|
8 | 9 | /** |
9 | 10 | * Framework-agnostic type token for capturing generic type information at runtime. |
@@ -60,22 +61,40 @@ public static <U> TypeToken<U> get(Class<U> clazz) { |
60 | 61 | } |
61 | 62 |
|
62 | 63 | /** |
63 | | - * Creates a TypeToken by extracting a type parameter from a generic superclass. |
| 64 | + * Creates a TypeToken by extracting a type parameter from a target ancestor class, walking up the class hierarchy. |
64 | 65 | * |
65 | | - * @param clazz the subclass to extract the type from |
66 | | - * @param typeParameterPosition the position of the type parameter in the superclass declaration (0-based) |
| 66 | + * @param clazz the subclass to start from |
| 67 | + * @param targetClass the ancestor class to extract the type parameter from |
| 68 | + * @param typeParameterPosition the position of the type parameter in the target class declaration (0-based) |
67 | 69 | * @param <U> the type to extract |
68 | | - * @param <V> the superclass type |
| 70 | + * @param <V> the starting class type |
69 | 71 | * @return a TypeToken representing the extracted type |
70 | 72 | */ |
71 | | - static <U, V> TypeToken<U> fromGenericSuperClass(Class<V> clazz, int typeParameterPosition) { |
72 | | - // Extract input type from generic superclass |
73 | | - var superClass = clazz.getGenericSuperclass(); |
74 | | - if (superClass instanceof ParameterizedType paramType) { |
75 | | - return new TypeToken<>(paramType.getActualTypeArguments()[typeParameterPosition]) {}; |
76 | | - } else { |
77 | | - throw new IllegalArgumentException("Cannot determine type from base class: " + clazz); |
| 73 | + static <U, V> TypeToken<U> fromGenericSuperClass(Class<V> clazz, Class<?> targetClass, int typeParameterPosition) { |
| 74 | + Class<?> current = clazz; |
| 75 | + |
| 76 | + while (current != null && current != Object.class) { |
| 77 | + var genericSuper = current.getGenericSuperclass(); |
| 78 | + if (!(genericSuper instanceof ParameterizedType paramType)) { |
| 79 | + current = current.getSuperclass(); |
| 80 | + continue; |
| 81 | + } |
| 82 | + |
| 83 | + Class<?> rawSuper = (Class<?>) paramType.getRawType(); |
| 84 | + if (rawSuper == targetClass) { |
| 85 | + Type typeArgument = paramType.getActualTypeArguments()[typeParameterPosition]; |
| 86 | + if (typeArgument instanceof TypeVariable) { |
| 87 | + throw new IllegalArgumentException( |
| 88 | + "Cannot determine type from base class, the type is left unresolved by an intermediate class: " |
| 89 | + + clazz); |
| 90 | + } |
| 91 | + return new TypeToken<>(typeArgument) {}; |
| 92 | + } |
| 93 | + |
| 94 | + current = rawSuper; |
78 | 95 | } |
| 96 | + |
| 97 | + throw new IllegalArgumentException("Cannot determine type from base class: " + clazz); |
79 | 98 | } |
80 | 99 |
|
81 | 100 | /** |
|
0 commit comments