我有一个带有主要方向的枚举类(北,东,南,西):
public enum Direction {
NORTH,
EAST,
SOUTH,
WEST;
}
有没有办法可以为同一件事使用多个名字?例如:
public enum Direction {
NORTH or N,
EAST or E,
SOUTH or S,
WEST or W;
}
在实践中,我想要的是能够并签署一个N或NORTH变量,并使两个操作完全相同。
示例:
Direction direction1=new Direction.NORTH;
Direction direction2=new Direction.N;
//direction1==direction2
答案 0 :(得分:10)
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;
}
是合法的,但"N"
不适用于自动生成的valueOf
方法。即Direction.valueOf("N")
会抛出IllegalArgumentException
,而不是返回Direction.NORTH
。
你也不能写case N:
。您必须使用switch
es中的全名,其值为Direction
。
除此之外,缩写形式应该与完整版本一样好。您可以在Direction.N
中使用EnumSet
,将其与Direction.N == Direction.NORTH
进行比较,获取name()
("NORTH"
),import static yourpackage.Direction.N;
等
答案 1 :(得分:5)
你可以这样做(省略东西方)。
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();
}
然后你就可以这样了
public void foo(Direction arg) {
Direction d = arg.getDirection();
}
然后你将永远只处理NORTH,SOUTH,EAST和WEST。
答案 2 :(得分:0)
嗯,也许有一个“客户端枚举”,其变量包含实际的“有意义的枚举”?
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;
}
有点矫枉过正,但您可以将Direction公开给客户端代码,并使用getBaseDirection
作为实际逻辑。