【发布时间】:2013-01-02 05:36:04
【问题描述】:
我正在使用以下代码从抽象类型(动物)列表中获取与给定类(狗、猫)匹配的第一个元素。还有其他类型安全的方法吗?
// get the first matching animal from a list
public <T extends Animal>T get(Class<T> type) {
// get the animals somehow
List<Animal> animals = getList();
for(Animal animal : animals) {
if(type.isInstance(animal)) {
// this casting is safe
return (T)animal;
}
}
// if not found
return null;
}
// both Cat and Dog extends Animal
public void test() {
Dog dog = get(Dog.class); // ok
Cat cat = get(Dog.class); // ok, expected compiler error
}
(猫和狗扩展了动物)
【问题讨论】:
-
job变量是什么? -
你是对的,第二行不应该编译,假设
Dog不扩展Cat。 -
刚刚更新了工作,对此感到抱歉
-
@Fallup:哦,来吧,type是一个对象,你不能那样做!
-
我在尝试您的代码 sn-p 时遇到编译错误:Type mismatch: cannot convert from Dog to Cat