This bites you in all sorts of ways. If Dog and Cat are subclasses of Animal, for example, I might want to use polymorphism to attempt to breed a hybrid animal with the loyalty of a cat and the stealth of a dog.
public Animal breed(Animal a, Animal b)
{
// do something here
}
public Animal breed(Dog a, Cat b)
{
//return null
}
But at compile time, if all I know is that I have two animals to breed, Java will ALWAYS pick the breed() method with the Animal arguments, even if the run-time types are Dog and Cat.
What to do? Certainly by now Java has some sort of dynamic_cast like in C++, right? Well, no. But hope isn't lost. The answer is Java's hideous reflection.
package polymorphismtest;
import java.lang.reflect.Method;
public class Main {
class AnimalHandler {
public void handleAnimals(Animal a, Animal b) {
System.out.println("Generic Animals");
}
public void handleAnimals(Dog a, Cat b) {
System.out.println("Dog and Cat");
}
}
class Animal { };
class Dog extends Animal { };
class Cat extends Animal { };
AnimalHandler h = new AnimalHandler();
Dog dog = new Dog();
Cat cat = new Cat();
private void doStuff(Animal a, Animal b) {
try
{
Method m = h.getClass().getDeclaredMethod("handleAnimals", a.getClass(), b.getClass());
m.invoke(h, a, b);
} catch (Exception e) {} //You should actually handle or throw these
}
public static void main(String[] args) {
Main a = new Main();
a.doStuff(a.dog, a.cat);
}
}
This is ugly, but it does work. Let me cross my fingers and pray that all these method calls get compiled down to sane native code when all is said and done.
0 comments:
Post a Comment