从 ParameterizedTypeImpl 获取 class 的列表类型

Getting List type of class from ParameterizedTypeImpl

我有一个 Map 字段,我正在尝试实例化它,看起来像这样

Map<Long, List<MyObj>>

转换它的代码是这个

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();
}

这与此相关 post 我读到:ClassCastException While casting List<String> to Class<?>

targetValueType

是一个 ParameterizedTypeImpl 对象。如果我在调试中查看该对象的值,它看起来像 java.util.List(MyObj path).

如何"know" 对象是一个列表,以便我可以进行转换?

更新

这是一个对象工厂,可将自动生成的域对象从 web 服务转换为 DTO 域对象。所以下面的代码是通用的,因此它应该能够处理任何类型的参数。

实例化应如下所示:

Map<Long, List<MyObj>> newMap;

...

if(mapType.isInterface()) {
    newMap = new HashMap<Long, List<MyObj>>();
} else {
    try {
        newMap = (Map<Long, List<MyObj>>) mapType.newInstance();
    } catch(Exception e) {
        newMap = new HashMap<Long, List<MyObj>>();
    }
}

我最终得到了以下代码

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();
}

if(targetMapParameterizedType.getActualTypeArguments()[1] instanceof ParameterizedType) {

ParameterizedType paramTypeImpl = (ParameterizedType) targetMapParameterizedType.getActualTypeArguments()[1];
Class<?> containerParam = (Class<?>) paramTypeImpl.getRawType();

if(containerParam.isInstance(new ArrayList<>()) && containerParam.isInterface()) {

    containerParam = new ArrayList<>().getClass();
    }
    targetValueType = containerParam;
} else {
    targetValueType = (Class<?>)targetMapParameterizedType.getActualTypeArguments()[1];
}

我必须获取 parameterizedTypeImple 对象的原始类型。然后检查它是否与列表和接口相关并将其用作 Class 对象。