我想声明一个枚举方向,它有一个返回相反方向的方法(以下语法不正确,即无法实例化枚举,但它说明了我的观点)。这在 Java 中可行吗?
代码如下:
public enum Direction {
NORTH(1),
SOUTH(-1),
EAST(-2),
WEST(2);
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
static Direction getOppositeDirection(Direction d){
return new Direction(d.getCode() * -1);
}
}
最佳答案
对于那些被标题吸引的人:是的,您可以在枚举中定义自己的方法。如果您想知道如何调用此类非静态方法,您可以像使用任何其他非静态方法一样执行此操作 - 您可以在定义或继承该方法的类型实例上调用它。在枚举的情况下,此类实例只是 ENUM_CONSTANT
s。
所以您只需要 EnumType.ENUM_CONSTANT.methodName(arguments)
。
现在让我们从问题回到问题。一种解决方案可能是
public enum Direction {
NORTH, SOUTH, EAST, WEST;
private Direction opposite;
static {
NORTH.opposite = SOUTH;
SOUTH.opposite = NORTH;
EAST.opposite = WEST;
WEST.opposite = EAST;
}
public Direction getOppositeDirection() {
return opposite;
}
}
现在 Direction.NORTH.getOppositeDirection()
将返回 Direction.SOUTH
。
这里有一点更“hacky”的方式来说明@jedwards comment但感觉不如第一种方法灵活,因为添加更多字段或更改它们的顺序会破坏我们的代码。
public enum Direction {
NORTH, EAST, SOUTH, WEST;
// cached values to avoid recreating such array each time method is called
private static final Direction[] VALUES = values();
public Direction getOppositeDirection() {
return VALUES[(ordinal() + 2) % 4];
}
}
关于Java 枚举方法 - 返回相反方向的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18883646/