我的代码中有一些部分如下所示:
A, B and C extend D
public ArrayList<A> getA() {
ArrayList<A> allElements = new ArrayList<A>();
for (D el : listOfDs) {
if (el instanceof A) {
allElements.add((A) el);
}
}
return allElements;
}
public ArrayList<B> getB() {
ArrayList<B> allElements = new ArrayList<B>();
for (D el : listOfDs) {
if (el instanceof B) {
allElements.add((B) el);
}
}
return allElements;
}
public ArrayList<C> getC() {
ArrayList<C> allElements = new ArrayList<C>();
for (D el : listOfDs) {
if (el instanceof C) {
allElements.add((C) el);
}
}
return allElements;
}
我想将所有这些组合成这样的一种方法:
public <T> ArrayList<T> get() {
ArrayList<T> allElements = new ArrayList<T>();
for (D el : listOfDs) {
if (el instanceof T) {
allElements.add((T) el);
}
}
return allElements;
}
这在Java中可能吗?
此刻我得到
无法对类型参数 T 执行 instanceof 检查。改用它的擦除对象,因为更多的泛型类型信息将在运行时被擦除
和
类型安全:从 Node 到 T 的未经检查的强制转换
然后我试过这个:
@SuppressWarnings("unchecked")
public <T> ArrayList<T> get(Class<T> clazz) {
ArrayList<T> allElements = new ArrayList<T>();
for(D o : listOfDs) {
if (o.getClass() == clazz) {
allElements.add((T) o);
}
}
return allElements;
}
它不会引发任何错误,但我该如何调用它?这不起作用:
get(A);