我有一个对象的ArrayList。需要查找对象列表是否具有特定感兴趣类的对象并检索它。 Java中是否有任何内置函数或其他实用程序可以直接检索此Object。请注意我希望避免使用迭代器循环。
示例:
List<Object> _list = new ArrayList<Object>();
//I am creating Objects using reflection and adding it to list
_list.add(object);
//Now i have a Class object of a particular class say ToolRun and pass it as argument
public Object getObjectFromList(Class c){
//this get function on list should find if list contains any Object of
//given Class name and retrieve it if found else should return null
return _list.get(c.getCanonicalName()) }
答案 0 :(得分:2)
Java 8 aproach可能是:
public List removeLastMovieWithGenre(List list, Class filterClazz){
return (List) list.parallelStream()
.filter(element -> filterClazz.isInstance(element))
.collect(Collectors.toList());
}
它返回一个带参数class的对象子列表。
答案 1 :(得分:0)
instanceof
关键字返回true。
示例:
Student s = new Student();
System.out.ptinln(s instanceof Student);
输出:true
所以你可以这样做
List list = getList();
if(list.get(0) instanceof Student) {
System.out.println("STUDENT");
} else if(list.get(0) instanceof Teacher) {
System.out.println("TEACHER");
}