如何在Java枚举中定义静态常量? [英] How to define static constants in a Java enum?
本文介绍了如何在Java枚举中定义静态常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要的是在一个地方定义字符串文字值对于BAR(1 ... n)值:
@RequiredArgsConstructor
public enum MyEnum {
BAR1(BAR_VALUE),
FOO(Foo),
BAR2(BAR_VALUE),
...,
BARn(BAR_VALUE);
private static final String BAR_VALUE =Bar;
@Getter
private final String value;
}
我在上面的代码中收到以下错误消息:无法引用
解决方案
正如IntelliJ IDEA在提取常量 - 建立静态内部类时建议的一样。这个方法有效:
@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常量{
public static final String BAR_VALUE =BAR;
}
}
Is there any way to define static final variables (effectively constants) in a Java enum declaration?
What I want is to define in one place the string literal value for the BAR(1...n) values:
@RequiredArgsConstructor
public enum MyEnum {
BAR1(BAR_VALUE),
FOO("Foo"),
BAR2(BAR_VALUE),
...,
BARn(BAR_VALUE);
private static final String BAR_VALUE = "Bar";
@Getter
private final String value;
}
I got the following error message for the code above: Cannot reference a field before it is defined.
解决方案
As IntelliJ IDEA suggest when extracting constant - make static inner class. This approach works:
@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";
}
}
这篇关于如何在Java枚举中定义静态常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文