How to get the REAL type parameter of a subclass of List?

obfish :

When I read the JavaFX source code, in com.sun.javafx.fxml.BeanAdapter, the static method getGenericListItemType(Type):

Determines the type of a list item.

However, with simple testcases, I found that this implementation may be flawed:

abstract class A<T> implements List<String> {}

abstract class B extends A<Integer> {}

abstract class C<S, T> implements List<T> {}

abstract class D extends C<String, Integer> {}

// in a function scope
BeanAdapter.getGenericListItemType(B.class) // expects String, gets Integer
BeanAdapter.getGenericListItemType(A.class) // works correctly

BeanAdapter.getGenericListItemType(D.class) // expects Integer, gets String

It turns out that this flawed implementation can only handle ideal conditions with the pattern of List<T> ← A<T> ← B<T> ← ... (parameterized) ... ← Y ← Z

However, when I tried to implement the function, I find it rather complicated. I wonder if it's possible to get the real type parameter. And if possible, could you provide some hints or a snippet?

Jorn Vernee :

Yes, this is possible.

You can create a Map<TypeVariable<?>, Class<?>> and walk the type graph starting at the given root class to fill in the concrete types supplied for each type variable. e.g.:

public static Map<TypeVariable<?>, Class<?>> findTypeParameterValues(Class<?> cls) {
    Map<TypeVariable<?>, Class<?>> parameterMap = new HashMap<>();
    findTypeParameterValues(parameterMap, cls);     
    return parameterMap;
}

private static void findTypeParameterValues(Map<TypeVariable<?>, Class<?>> map, Class<?> cur) {
    // create list of parameterized super types
    List<ParameterizedType> pTypes = genericSuperTypes(cur)
        .filter(ParameterizedType.class::isInstance)
        .map(ParameterizedType.class::cast)
        .collect(Collectors.toList());

    for(ParameterizedType pType : pTypes) {     
        Type[] tArgs = pType.getActualTypeArguments(); // provided type arguments
        Class<?> rawType = (Class<?>) pType.getRawType(); // (always a Class<?>)
        TypeVariable<?>[] tParams = rawType.getTypeParameters(); // type parameters

        for(int i = 0; i < tArgs.length; i++) { // iterate over both
            Type tArg = tArgs[i]; // match type argument...
            TypeVariable<?> tParam = tParams[i]; // with type parameter
            Class<?> arg; // the value for the parameter
            if(tArg instanceof Class<?>) {
                 // concrete argument
                arg = (Class<?>) tArg;
            } else if(tArg instanceof TypeVariable<?>) {
                 // concrete argument provided previously, or null
                arg = map.get((TypeVariable<?>) tArg);
            } else {
                throw new UnsupportedOperationException("Unsupported type argument type: " + tArg);
            }
            map.put(tParam, arg); // put found value in map
        }
    }

    superClasses(cur).forEach(pt -> findTypeParameterValues(map, pt));
}

private static Stream<Class<?>> superClasses(Class<?> cls) {        
    Stream.Builder<Class<?>> ret = Stream.builder();
    ret.add(cls.getSuperclass());
    Arrays.stream(cls.getInterfaces()).forEach(ret::add);
    return ret.build().filter(Objects::nonNull);
}

private static Stream<Type> genericSuperTypes(Class<?> cls) {
    Stream.Builder<Type> ret = Stream.builder();
    ret.add(cls.getGenericSuperclass());
    Arrays.stream(cls.getGenericInterfaces()).forEach(ret::add);
    return ret.build().filter(Objects::nonNull);
}

Then to use the result for your particular case you could get the concrete value for the type variable of List from the map:

public static void main(String[] args) throws Throwable {
    System.out.println(getGenericListItemType(B.class)); // class java.lang.String
    System.out.println(getGenericListItemType(A.class)); // class java.lang.String
    System.out.println(getGenericListItemType(D.class)); // class java.lang.Integer
}

private static final TypeVariable<?> listE = List.class.getTypeParameters()[0];

public static Class<?> getGenericListItemType(Class<?> cls) {  
    // method defined in 'Reflection' helper class      
    return Reflection.findTypeParameterValues(cls).get(listE);
}

Note that if there is no concrete definition for the particular type variable, the map will contain null as a value for that type variable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159687&siteId=1