今天我遇到了一个让我非常想知道的函数。因此,让我们假设这个简单的结构以进行澄清。
public class Animal{
public String getName(){ return null; }
}
public class Dog extends Animal{
@Override
public String getName(){
//I'm aware that not any Dog's name is 'Pluto', but its just a Sample ;)
return "Pluto"
}
}
public class Cat extends Animal{
protected final String mName;
public Cat(String name){
mName = name;
}
@Override
public String getName(){
//cats have different names, because the internet loves cats
return mName;
}
public void miao(){
//just a dummy
}
}
现在将 a 分配Dog
给一个Animal
指针是绝对有效的,但像这样将一个分配Animal
给一个Dog
指针是无效的:
Animal animal = new Dog(); //valid, any Dog is at least an Animal
Dog dog = new Animal(); // invalid, of course not any Animal is a Dog!
让我们假设一个 AnimalCage 类,其中“魔术”发生:
public class AnimalCage{
private ArrayList<Animal> mCage = new ArrayList<Animal>();
public addAnimal(Animal animal){
mCage.add(animal);
}
// HERE is where the "Magic" happens:
public <A extends Animal> A getAnimalByName(String name){
//try catch block not mandatory
try{
for (Animal a: mCage){
if (name.equals(a.getName()) return (A)a;
}
} catch(ClassCastException cce){}
return null;
}
}
使用AnimalCage
可以做到这一点:
//all valid
AnimalCage cage = new AnimalCage();
Dog dog = new Dog();
Cat cat = new Cat("Mauzi");
Cat cat2 = new Cat("Garfield");
cage.add(dog);
cage.add(cat);
cage.add(cat2);
// and later get it back
//will return dog
Dog pluto = cage.getAnimalByName("Pluto");
//will find nothing and return null
Dog snoopy = cage.getAnimalByName("Snoopy);
//will raise ClassCastException and return null
snoopy = cage.getAnimalByName("Mauzi");
//will return Mauzi
Animal mauzi = cage.getAnimalByName("Mauzi");
所以我可以在不显式转换的情况下做任何事情。这使我得出这样的假设,即Erasures
在运行时不会被删除,尽管我知道得更好。在我认为我必须至少给出一个关于像这个函数一样投射什么的指标之前:
public <A extends Animal> A getAnimalByName(String name, Class<A> animalClass){
try{
for (Animal a: mCage){
if (name.equals(a.getName()) return (A)a; }
} catch(ClassCastException cce){}
return null;
}
//use
Dog dog = cage.getAnimalByName("Pluto", Dog.class);
我真的很想知道 Java 如何让我在猫/狗上分配动物,以及它必须投射的动物的专业化