2

我的代码中有一些部分如下所示:

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);
4

1 回答 1

5

你可以Iterables.filter从番石榴中使用。

示例用法:

Iterable<X> xs = Iterables.filter(someIterable, X.class);

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

于 2012-06-09T10:20:05.130 回答