Attribute value must be constant !!!
1 min readMay 20, 2021
When I’m going to use constant as a parameter from an Enum I got this compilation error.’ Attribute value must be constant’
This is the Enum class,
public enum Fruits {
APPLE("A", "Apple");
ORANGE("O", "Orange"); String code;
String value;
Fruits(String code, String value) {
this.code = code;
this.value = value;
}
public static String getValue(String code) {
for (Fruits b : Fruits.values()) {
if (b.code.equalsIgnoreCase(code)) {
return b.value;
}
}
return null;
}
}
When we access an Enum value using Fruits.APPLE.getValue(), it will show as and error as Attribute value must be constant.
To resolve this error what we can add a constant class in to Enum class. like this
public enum Fruits {
APPLE("A", Constants.APPLE_VALUE );
ORANGE("O",Constants.ORANGE_VALUE); String code;
String value;
Fruits(String code, String value) {
this.code = code;
this.value = value;
}
public static String getValue(String code) {
for (Fruits b : Fruits.values()) {
if (b.code.equalsIgnoreCase(code)) {
return b.value;
}
}
return null;
}public static class Constants {
public static final String APPLE_VALUE = "Apple";
public static final String ORANGE_VALUE = "Orange"; }
}