Java:我可以在枚举中使用两个不同的名称来算作同一事物吗?
我有一个带有基本方向(北、东、南、西)的枚举类:
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
I have an enum class with the cardinal directions(North, East, South, West):
public enum Direction {
NORTH,
EAST,
SOUTH,
WEST;
}
Is there a way to be able to use multiple names for the same thing? For example something like this:
public enum Direction {
NORTH or N,
EAST or E,
SOUTH or S,
WEST or W;
}
In practice what I want is to be able and sign to a variable either N or NORTH and have the two operations be exactly the same.
Example:
Direction direction1=new Direction.NORTH;
Direction direction2=new Direction.N;
//direction1==direction2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是合法的,但
"N"
不适用于自动生成的valueOf
方法。即Direction.valueOf("N")
将抛出IllegalArgumentException
而不是返回Direction.NORTH
。您也不能编写
case N:
。您必须在值为Direction
的switch
中使用全名。除此之外,缩写形式应该与完整版本一样有效。您可以在
EnumSet
中使用Direction.N
,比较其是否相等Direction.N == Direction.NORTH
,获取其名称()
(即"NORTH"
)、import static yourpackage.Direction.N;
等。is legal, but
"N"
will not work with the auto-generatedvalueOf
method. I.e.Direction.valueOf("N")
will throw anIllegalArgumentException
instead of returningDirection.NORTH
.You also cannot write
case N:
. You have to use the full names inswitch
es whose value is aDirection
.Other than that, the abbreviated form should work just as well as the full version. You can use
Direction.N
inEnumSet
s, compare it for equalityDirection.N == Direction.NORTH
, get itsname()
(which is"NORTH"
),import static yourpackage.Direction.N;
, etc.你可以做这样的事情(省略了东和西)。
那么你可以像这样
然后你将永远只处理北、南、东和西。
You could do something like this (East and West omitted).
Then you could something like this
Then you will always be dealing with only NORTH, SOUTH, EAST, and WEST.
嗯,也许有一个“客户端枚举”,其中包含保存实际“有意义的枚举”的变量?
有点矫枉过正,但您可以将 Direction 公开给客户端代码并使用
getBaseDirection
来实现实际逻辑。Hum, maybe having a "client Enum" with variables that hold the actual "meaningful Enum"?
Kinda overkill, but you can expose Direction to client code and use
getBaseDirection
for actual logic.