lundi 8 juin 2015

Getting List type of class from ParameterizedTypeImpl

I have a field of Map I am trying instantiate that looks like this

Map<Long, List<MyObj>>

The code to convert it is this

ParameterizedType targetMapParameterizedType = (ParameterizedType) targetMethodMap.get(targetMethodName).getGenericParameterTypes()[0];
Class<?> mapType = targetMethodMap.get(targetMethodName).getParameterTypes()[0];
if(mapType.isInterface()) {
    newMap = new HashMap<Object, Object>();
} else {
    try {
        newMap = (Map<Object, Object>) mapType.newInstance();
    } catch(Exception e) {
        newMap = new HashMap<Object, Object>();
    }
}
Class<?> targetKeyType = null;
Class<?> targetValueType = null;
try {
    targetKeyType = (Class<?>)targetMapParameterizedType.getActualTypeArguments()[0];
} catch (ClassCastException cce) {
    cce.printStackTrace();
}
try {
    targetValueType = (Class<?>)targetMapParameterizedType.getActualTypeArguments()[1];
} catch (ClassCastException cce) {
    cce.printStackTrace();
}

This is related to this post I read: ClassCastException While casting List<String> to Class<?>.

targetValueType

is a ParameterizedTypeImpl object. If I look at the value of that object in debug it looks like java.util.List(MyObj path).

How do "know" that the object is a list progromatically so I can do the conversion?





Aucun commentaire:

Enregistrer un commentaire