如何从Java List中获取一种类型的所有实例?

Mar*_*oma 2 java generics

我的代码中有一些部分看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

我想将它们全部组合成一个这样的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

这在Java中可行吗?

目前我得到了

无法对类型参数T执行instanceof检查.请改为使用其擦除对象,因为将在运行时擦除其他泛型类型信息

类型安全:从节点到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;
}
Run Code Online (Sandbox Code Playgroud)

它不会抛出任何错误,但我该怎么称呼呢?这不起作用:

get(A);
Run Code Online (Sandbox Code Playgroud)

mis*_*tor 5

你可以使用Iterables.filterGuava.

用法示例:

Iterable<X> xs = Iterables.filter(someIterable, X.class);
Run Code Online (Sandbox Code Playgroud)

由于它是一个开源库,您可以查看源代码以找出您做错了什么.