这是一些带有 get()
方法的枚举。
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();
}
}
问题是如何改进以返回特定类型的动物而不使用枚举外部的类型转换。当然我可以使用像
这样的方法public <T extends Animal> T get(Class<T> clazz) { return (T) get(); }
但也许还有不那么笨拙的方法。
最佳答案
此答案基于这样的假设:您实际上不需要 CHLOE、LUNA 或 SNICKERS 的单独的 Cat
实例。此外,由于您的 Animals 没有任何方法或状态,因此看起来您并不真正需要它们作为单独的类。所以也许这样的事情会更容易:
public enum AnimalType {
Cat, Dog, Parrot;
}
public enum Animals {
CHLOE(AnimalType.Cat),
MOLLY(AnimalType.Dog),
LUNA(AnimalType.Cat),
TOBY(AnimalType.Dog),
ZOE(AnimalType.Parrot),
SNICKERS(AnimalType.Cat);
private final AnimalType type;
Animals(AnimalType type) {
this.type = type;
}
public AnimalType get() {
return type;
}
}
关于 java 。使用枚举中的泛型获取特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794767/