Here is some enum with get() method.
public class ZooTest {
public enum Animals {
CHLOE("cat"),
MOLLY("dog"),
LUNA("cat"),
TOBY("dog"),
ZOE("parrot"),
SNICKERS("cat");
private final String type;
Animals(String type) {
this.type = type;
}
public class Animal {
}
public class Cat extends Animal {
}
public class Dog extends Animal {
}
public class Parrot extends Animal {
}
public Animal get() {
return "cat".equals(type)
? new Cat()
: "dog".equals(type)
? new Dog()
: new Parrot();
}
}
@Test
public void shouldReturnSpecificClass() {
assertTrue(Animals.CHLOE.get() instanceof Cat);
}
@Test(expectedExceptions = {ClassCastException.class})
public void shouldReturnSpecificClass2() {
Dog dog = (Dog) Animals.CHLOE.get();
}
}
The question is how can it be improved to return specific type of animal without using type casting outside enum. Of course I can use methods like
public <T extends Animal> T get(Class<T> clazz) { return (T) get(); }
but maybe there is less clumsy way.
Cat.class).