Java: Can I use two different names in an enum to count as the same thing?
我有一个具有主要方向(北、东、南、西)的枚举类:
1 2 3 4 5 6 | public enum Direction { NORTH, EAST, SOUTH, WEST; } |
有没有一种方法可以为同一件事使用多个名称?例如:
1 2 3 4 5 6 | public enum Direction { NORTH or N, EAST or E, SOUTH or S, WEST or W; } |
实际上,我想要的是能够对一个变量n或north进行签名,并使这两个操作完全相同。
例子:
1 2 3 | Direction direction1=new Direction.NORTH; Direction direction2=new Direction.N; //direction1==direction2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | public enum Direction { NORTH, EAST, SOUTH, WEST, ; // Convenience names. public static final Direction N = NORTH; public static final Direction E = EAST; public static final Direction S = SOUTH; public static final Direction W = WEST; } |
是合法的,但
你也不能写
除此之外,缩写形式应该和完整版本一样有效。你可以在
你可以这样做(省略了东西方)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public enum Direction { NORTH { @Override Direction getDirection() { return NORTH; } }, N { @Override Direction getDirection() { return NORTH; } }, SOUTH { @Override Direction getDirection() { return SOUTH; } }, S { @Override Direction getDirection() { return SOUTH; } } ; abstract Direction getDirection(); } |
然后你可以做这样的事
1 2 3 | public void foo(Direction arg) { Direction d = arg.getDirection(); } |
那么你将永远只处理北方、南方、东方和西方。
嗯,也许有一个"客户机枚举",变量包含实际的"有意义的枚举"?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public enum Direction { NORTH(BaseDirection.NORTH), N(BaseDirection.NORTH), EAST(BaseDirection.EAST), E(BaseDirection.EAST), SOUTH(BaseDirection.SOUTH), S(BaseDirection.SOUTH), WEST(BaseDirection.WEST), W(BaseDirection.WEST); private BaseDirection baseDirection; private Direction(BaseDirection baseDirection) { this.baseDirection = baseDirection; } public BaseDirection getBaseDirection() { return baseDirection; } } public enum BaseDirection { NORTH, EAST, SOUTH, WEST; } |
有点过分,但您可以向客户机代码公开方向,并使用