Possible Duplicate:
Regarding factory design pattern through reflection
I was doing R&D on factory pattern I have developed the below code. Right now I know the subclasses are Dog and Cat, but please advise me. What to do if I want to achieve the same thing through reflection by passing the class name in main.java?
Animal
public abstract class Animal {
public abstract String makeSound();
}
Dog
public class Dog extends Animal {
@Override
public String makeSound() {
return "Woof";
}
}
Cat
public class Cat extends Animal {
@Override
public String makeSound() {
return "Meow";
}
}
AnimalFactory
public class AnimalFactory {
public Animal getAnimal(String type) {
if ("canine".equals(type)) {
return new Dog();
} else {
return new Cat();
}
}
}
Main
public class Main {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();
Animal a1 = animalFactory.getAnimal("feline");
System.out.println("a1 sound: " + a1.makeSound());
Animal a2 = animalFactory.getAnimal("canine");
System.out.println("a2 sound: " + a2.makeSound());
}
}
Please advise it how I can add reflection functionality into it so that I don’t need to even determine the type, just pass the class name in the main java and object of that subclass gets created.
If you pass the fullyqualified name of the class, you can instantiate them as following:
To avoid ClassCastException, you could test that the returned class of
Class.forName()is indeed a subclass ofAnimalbefore invokingnewInstance(). UseisAssignableFromfor that.