在我的枚举构造函数中,我正在尝试初始化他们的成员。我需要使用switch语句来知道当前正在实例化哪个枚举。但是由于某些原因,this
似乎返回null
,这对我来说毫无意义。在构造函数完成之前是this
null
吗?如果是这样,我如何区分运行时构建的枚举?以下示例是我实际代码的简化版本,用于演示此问题。
Food f = Food.APPLE;
System.out.println(f.getTastes());
Food Enum
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
答案 0 :(得分:4)
我不确定这是否适合你,但我相信是正确的模式,而不是弄清楚每种食物在构造函数中的味道,你可以宣布它。
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
}
}