我不認爲它支持開箱即用。然而,這是很容易與只有幾行代碼添加:
<T> List<T> ofType(List<? extends T> collection, Class<? extends T> clazz) {
List<T> l = new LinkedList<T>();
for (T t : collection) {
Class<?> c = t.getClass();
if (c.equals(clazz)) {
l.add(t);
}
}
return l;
}
例如:
import java.util.*;
public class SubListByType {
class Animal {
String breed;
Animal(String breed) {
this.breed = breed;
}
String getBreed() {
return breed;
}
}
class Dog extends Animal {
Dog(String breed) {
super(breed);
}
}
class Cat extends Animal {
Cat(String breed) {
super(breed);
}
}
<T> List<T> ofType(List<? extends T> collection, Class<? extends T> clazz) {
List<T> l = new LinkedList<T>();
for (T t : collection) {
Class<?> c = t.getClass();
if (c.equals(clazz)) {
l.add(t);
}
}
return l;
}
void snoopDogs() {
Animal[] animals = { new Dog("Greyhound"), new Cat("Lion"), new Dog("Japanese Spitz") };
for(Animal x : animals) {
System.out.println(x.getClass().getCanonicalName() + '\t' + x.getBreed());
}
System.out.println();
// LOOK HERE
for (Animal x : ofType(Arrays.asList(animals), Dog.class)) {
System.out.println(x.getClass().getCanonicalName() + '\t' + x.getBreed());
}
}
public static void main(String[] args) {
SubListByType s = new SubListByType();
s.snoopDogs();
}
}
謝謝,只需要使用'Arrays.asList'因此它可以是可迭代。雖然Iterables看起來並不像C#的OfType那樣快捷,但無論如何都可以作爲單線程來使用:-)(Dog d:Iterables.filter(Arrays.asList(animals),Dog.class)){ – Hao 2012-03-07 02:44:36