在Java <1.5中,常量将像这样实现
public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
并且您可以像这样使用它:
MyClass myClass = new MyClass(MyClass.VERTICAL);
现在,显然在1.5中,您应该使用枚举:
public class MyClass {
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
现在您可以像这样使用它:
MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
我觉得有点难看。现在,我可以轻松添加几个静态变量:
public class MyClass {
public static Orientation VERTICAL = Orientation.VERTICAL;
public static Orientation HORIZONTAL = Orientation.HORIZONTAL;
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
现在,我可以再次执行此操作:
MyClass myClass = new MyClass(MyClass.VERTICAL);
具有枚举的所有类型安全性。
这是好风格还是坏风格?您能想到更好的解决方案吗?
更新资料
Vilx-是第一个强调我所缺少的东西的人-枚举应该是一等公民。在Java中,这意味着它将在包中获取自己的文件-
我们没有名称空间。我本来以为这会有点重量级,但是实际上做到了,确实感觉不错。
Yuval的回答很好,但是并没有真正强调非嵌套枚举。另外,对于1.4-JDK中有很多使用整数的地方,我确实在寻找一种方法来发展这种代码。