抱歉,如果这个问题很简单,或者以前已经回答过了,我是Java新手,在我的研究中,我找不到关于这个问题的太多信息,也还没有找到解决方案.
我有一个具有多个类的ArrayList,这些类都共享一个公共接口,在本例中该接口称为"Packable".我正在try 创建一个方法,该方法接受一个类参数并遍历此ArrayList的每个元素,returning a new list containing all the items in the original list that are of the same class as the reference parameter.
到目前为止,这是我的代码,try instanceof方法:
public List<Packable> getOfType(Packable reference){
List<Packable> typeOfItems = new ArrayList<>();
for (Packable item: itemsStored) {
if (item instanceof reference){
typeOfItems.add(item);
}
}
return typeOfItems;
}
这是抛出一个错误,因为它还不能将引用识别为类.This question提到一种方法isAssignableFrom,其答案是:"When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime."(感谢Marc Novakowski)
我知道,考虑到这个参数,这个类在编译时是未知的,因此我try 实现isAssignableFrom,但似乎不能真正让它工作.IDE并没有真正识别或建议它,在线上也没有太多关于该方法的内容.我试着按照Java文档建议的方式实现它,但这也不起作用:
if (reference.isAssignableFrom(item.getClass())){
typeOfItems.add(item);
}
任何有关调查方法的帮助或建议都将不胜感激.感谢你阅读这个问题,如果这个问题很简单,或者已经在其他地方得到了回答,我刚刚错过了,我再次表示歉意.谢谢大家