以下方法是有问题的:
> public Class<List<String>> getModelType() {
> return (Class<List<String>>) new ArrayList<String>().getClass();
> }
例如,如果你想测试一个对象是否属于类型
org.eclipse.emf.common.util.BasicEList<String>
是类型
List<String>
基于上述 getModelType() 方法的结果,例如:
BasicEList<String> fromObject = ...;
if (getModelType().isAssignableFrom(fromObject.getClass())) {
transferFromModelToUi(getModelType().cast(fromObject));
}
它会导致 false 而它应该是 true 因为两个对象都实现了接口 List(因为 getModelType() 返回一个 List 类型的 Class 对象而不是 ArrayList)。
这是一种对我有用的方法(有点麻烦,但在上面的示例中会导致正确的结果,可以移动到静态初始化程序):
public Class<List<String>> getModelType() {
Class<?> arrayListClass = new ArrayList<String>().getClass();
Class<?>[] interfaces = arrayListClass.getInterfaces();
int index = 0;
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i].equals(List.class)) {
index = i;
break;
}
}
return (Class<List<String>>) interfaces[index];
}