Java >> Java Tutorial >  >> Tag >> static

Wie definiere ich statische Konstanten in einer Java-Enumeration?

Wie IntelliJ IDEA beim Extrahieren von Konstanten vorschlägt - erstellen Sie eine statische verschachtelte Klasse. Dieser Ansatz funktioniert:

@RequiredArgsConstructor
public enum MyEnum {
    BAR1(Constants.BAR_VALUE),
    FOO("Foo"),
    BAR2(Constants.BAR_VALUE),
    ...,
    BARn(Constants.BAR_VALUE);



    @Getter
    private final String value;

    private static class Constants {
        public static final String BAR_VALUE = "BAR";
    }
}

public enum MyEnum {
    BAR1(MyEnum.BAR_VALUE);

    public static final String BAR_VALUE = "Bar";

funktioniert gut


public enum MyEnum {
//  BAR1(       foo),   // error: illegal forward reference
//  BAR2(MyEnum.foo2),  // error: illegal forward reference
    BAR3(MyEnum.foo);   // no error

  public static final int foo =0;
  public static       int foo2=0;
  MyEnum(int i) {}

  public static void main(String[] args) { System.out.println("ok");}
}

Dies kann ohne eine innere Klasse für die Konstante erfolgen.


Java-Tag