How to define Constant values
I have two ways to define constants. First one holds the bunch of static final DataType variables in a class and another by using Enum.
Here is the fist type:
public class TipTipProperties {
public static final String MAX_WIDTH_AUTO = "auto";
public static final String POSITION_RIGHT = "right";
}
And the usage of these variable will via static call, as an example: TipTipProperties.MAX_WIDTH_AUTO
And the second type is:
public enum TipTipProperties {
MAX_WIDTH_AUTO(MaxWidth.AUTO),
POSITION_RIGHT(Position.RIGHT);
private MaxWidth maxWidth;
private Position position;
private TipTipProperties(MaxWidth maxWidth) {
this.maxWidth = maxWidth;
}
private TipTipProperties(Position position) {
this.position = position;
}
public MaxWidth getMaxWidth() {
return maxWidth;
}
public Position getPosition() {
return position;
}
public enum MaxWidth {
AUTO("auto");
private String width;
private MaxWidth(String width) {
this.width = width;
}
public String getWidth() {
return width;
}
}
public enum Position {
RIGHT("right"),
private String position;
private Position(String position) {
this.position = position;
}
public String getPosition() {
return position;
}
}
}
As an example usage: TipTipProperties.POSITION_RIGHT.getPosition().getPosition()
.
My question is:
Thanks in advance.
Enum is the best to do this as Joshua Bloch said in Effective Java,you will have more control using Enum like if you want to print all constants,you can. with class constants you can not have type safety.read this for further help
Using a properties file in your project would also be a good way of doing this. How to do that in Java is explained at this post.
You could basically create something called tiptip.properties
in the root directory of your project and then store all the key-value pairs that you need.
上一篇: 从空值创建默认对象:PHP 5.4
下一篇: 如何定义常量值