Java Enum Static Final Instance Variables

2022-09-03 03:30:36

哎呀!

这段代码工作了一段时间,然后我决定添加一个默认颜色,它停止工作了。我收到以下错误:

1 error found:
File: Status.java  [line: 20]
Error: Status.java:20: illegal reference to static field from initializer

在编译时使用以下代码。

import java.awt.Color;

enum Status
{
  OFF ("Off"),
  TRAINING ("Training", new Color(255, 191, 128)),
  BEGINNER ("Beginner", new Color(128, 255, 138)),
  INTERMEDIATE ("Intermediate", new Color(128, 212, 255)),
  ADVANCED ("Advanced", new Color(255, 128, 128));

  public final String name;
  public final Color color;

  public static final Color defaultColor = Color.WHITE;

  Status(String name)
  {
    this(name, defaultColor);
  }
  Status(String name, Color color)
  {
    this.name = name;
    this.color = color;
  }
}

据我所知,这应该有效,但无论出于何种原因,Java决定抛出一个错误。有什么想法吗?


答案 1

defaultColor只有在调用构造函数才会初始化 - 因此在此之前它将具有其默认值(null)。一种选择是将默认颜色放在嵌套类型中:

import java.awt.Color;

enum Status
{
  OFF ("Off"),
  TRAINING ("Training", new Color(255, 191, 128)),
  BEGINNER ("Beginner", new Color(128, 255, 138)),
  INTERMEDIATE ("Intermediate", new Color(128, 212, 255)),
  ADVANCED ("Advanced", new Color(255, 128, 128));

  public final String name;
  public final Color color;

  Status(String name)
  {
    this(name, Defaults.COLOR);
  }
  Status(String name, Color color)
  {
    this.name = name;
    this.color = color;
  }

  private static class Defaults
  {
     private static Color COLOR = Color.WHITE;
  }
}

当然,如果您在代码中只引用一次默认颜色,则最好在构造函数调用中对其进行硬编码:

Status(String name)
{
  this(name, Color.WHITE);
}

答案 2

枚举常量必须首先初始化。若要初始化它们,必须调用构造函数。第一个构造函数引用在调用时不可能已初始化的静态字段。


推荐