Is it possible to artificially create a ParameterizedType
object that would be the definition of a collection of a particular specified type? If I have a named Collection field I can have the proper definition, ie. for field in a class like this
public class MyContainerClass {
List<String> myElementsList;
}
I can extract all the information I need through the following code.
public class GetGenericsTest {
public static class MyContainerClass {
List<String> myElementsList;
}
public static void main(String[] args) throws Exception {
Field field = MyContainerClass.class.getDeclaredField("myElementsList");
ParameterizedType pt = (ParameterizedType) field.getGenericType();
System.out.println("collection type: " + pt.getRawType().getTypeName());
System.out.println("elt type: " + ((Class<?>)pt.getActualTypeArguments()[0]).getName());
}
}
which produces:
collection type: java.util.List
elt type: java.lang.String
But I can't figure out how to create such a ParameterizedType
through Reflection only.
In other words, I need a generic solution so that the following test code would pass:
Class<?> elementClass = MyElement.class;
ParameterizedType parameterizedType = implementMe(elementClass, List.class);
Assertions.assertEquals(List.class.getName(), parameterizedType.getRawType().getTypeName());
Assertions.assertEquals(elementClass.getName(), ((Class<?>)pt.getActualTypeArguments()[0]).getName());