Reputation: 27899
Constants given in the following enum
,
enum StringConstatns {
ONE {
@Override
public String toString() {
return "One";
}
},
TWO {
@Override
public String toString() {
return "Two";
}
}
}
public final class Main {
public static void main(String... args) {
System.out.println(StringConstatns.ONE + " : " + StringConstatns.TWO);
}
}
can be accessed just like StringConstatns.ONE
and StringConstatns.TWO
as shown in the main()
method.
I have the following enum
representing an int
constant(s).
public enum IntegerConstants
{
MAX_PAGE_SIZE(50);
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This requires accessing the constant value like IntegerConstants.MAX_PAGE_SIZE.getValue()
.
Can this enum
be modified somehow in a way that value
can be accessed just like IntegerConstants.MAX_PAGE_SIZE
as shown in the first case?
Upvotes: 1
Views: 122
Reputation: 19002
The answer is no, you cannot. You have to call:
IntegerConstants.MAX_PAGE_SIZE.getValue()
If you really want a shortcut, you could define a constant somewhere like this:
public class RealConstants {
final public static int MAX_PAGE_SIZE = 50;
}
public enum IntegerConstants
{
MAX_PAGE_SIZE(RealConstants.MAX_PAGE_SIZE);//reuse the constant
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
Upvotes: 4
Reputation: 5846
This is not going to work because your first example does implicit calls to .toString()
when you concatenate them with +
, whereas there is no implicit conversion to int
which is needed for your second example.
You could define them as static final
fields, this does exactly what you are searching for:
public class IntegerConstants {
public static final int MAX_PAGE_SIZE = 50;
}
Upvotes: 2