实际上有一种方法不需要手动投射每个项目(虽然它仍然很丑......)
//start with an arraylist of unknown generic type
ArrayList <Object> obj = getData();
//Make an array from it(basically the same as looping over the list
// and casting it to the real type of the list entries)
Object[] objArr = obj.toArray();
//Check if the array is not empty and if the componentType of the
//array can hold an instance of the class Person
if(objArr.length>0
&& objArr.getClass().getComponentType().isAssignableFrom(Person.class)) {
// do sth....
}
这不应该给出任何未经检查的警告。
你可以像这样使用它:
private boolean isArrayOfType(Object[] array,Class<?> aClass) {
return array.length > 0
&& array.getClass().getComponentType().isAssignableFrom(aClass);
}
Object[] personArr = getData().toArray();
if(isArrayOfType(personArr,Person.class) {
//Do anything...
}
以下是行不通的:
// -> This won't work, sry!
ArrayList<Person> personArrayList = Arrays.asList((Person[])personArr);