dimanche 29 août 2021

Is there a way to extract the type parameters of a list inside a list in Java?

I'm trying to find out if there is a way to get the parameters of a type such as List that is nested inside another List.

For example, how would you extract the type of a nested List from a field such as this:

List<List<String>> strings

I found a way to do this one level deep:

for (Field field : aClass.getDeclaredFields()) {
    //checking if field type can have parameters, for example List<String>
    if(List.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
        //extracting type parameters, to do this you need to cast a type to ParameterizedType and then to Class to get a simple name easily
        List<Class<?>> typeParameters = Stream.of(((ParameterizedType) field.getGenericType()).getActualTypeArguments())
                .map(type -> (Class<?>) type)
                .collect(Collectors.toList());

        //for a field like List<String> strings; this will print out: strings: List<String>
        System.out.println(field.getName() + ": " +
                        field.getType().getSimpleName() + "<" +
                        typeParameters.stream().map(Class::getSimpleName).collect(Collectors.joining(", ")) +
                        "> ");

    }
}

However, I haven't had any success with scaling it up for nested types.





Aucun commentaire:

Enregistrer un commentaire