在我的枚举构造函数中,我正在尝试初始化其成员。我需要使用开关语句来知道当前正在实例化的枚举。但是,由于某种原因,this
似乎返回null
,这对我来说毫无意义。this
null
是否完成构造函数?如果是这样,我该如何区分运行时间正在构建哪些枚举?下面的示例是我实际代码的简化版本,以说明问题。
Food f = Food.APPLE;
System.out.println(f.getTastes());
食物枚举
public enum Food
{
APPLE,
PANCAKES,
PASTA;
private List<String> tastes = new ArrayList<>();
Food()
{
switch(this)
{
case APPLE:
tastes.add("Sour");
tastes.add("Sweet");
break;
case PANCAKES:
tastes.add("Dough-y");
break;
case PASTA:
tastes.add("Creamy");
tastes.add("Rich");
tastes.add("Velvet");
}
}
public List<String> getTastes()
{
return tastes;
}
}
我得到以下异常
Exception in thread "main" java.lang.ExceptionInInitializerError
at Food.<init>(Food.java:18)
at Food.<clinit>(Food.java:10)
at Tester.main(Tester.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
at Food.values(Food.java:8)
at Food$1.<clinit>(Food.java:18)
... 8 more
我不确定这是否适合您,但我相信是正确的模式,而不是弄清每种食物在构造方中具有什么口味,而是可以声明。/p>
public enum Food
{
APPLE("good", "sweet"),
PANCAKES("delicious","omg"),
PASTA("too fat", "but its gud");
private List<String> tastes = new ArrayList<>();
Food(String ... tastes) {
// add to the list
}
}