vendredi 2 octobre 2020

Create Class object of a Collection of a given class

Is it possible to artificially create a Class 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 a field like

List<MyElement> myElementsList;

I can extract all the information I need. But I can't figure out how to create such a Class through Reflection only.

In other words, I need a generic solution so that the following test code would pass:

Class<?> elementClass = MyElement.class;

Class<?> collectionOfMyElements = implementMe(elementClass, List.class);

Assertions.assertEquals(List.class, collectionOfMyElements);

Type genericSuperclass = containerClass.getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
Type derivedElementType = actualTypeArguments[0];

Assertions.assertEquals(elementClass, derivedElementType);




Aucun commentaire:

Enregistrer un commentaire