【发布时间】:2015-06-10 02:45:46
【问题描述】:
我有一个我正在尝试实例化的 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();
}
这与我阅读的这篇文章有关:ClassCastException While casting List<String> to Class<?>。
targetValueType
是一个 ParameterizedTypeImpl 对象。如果我在调试中查看该对象的值,它看起来像 java.util.List(MyObj path)。
如何以程序方式“知道”对象是一个列表,以便我可以进行转换?
更新
这是一个对象工厂,将自动生成的域对象从 web 服务转换为 DTO 域对象。所以下面的代码是通用的,所以它应该能够处理任何类型的参数。
【问题讨论】:
标签: java generics reflection