枚举继承或类似的东西
我有一个字符串(这是一条消息)作为输入,我需要根据该字符串执行 4 种可能的操作之一 我知道有 eum.valueOf() 选项,但我有 4 个不同的枚举,每个枚举都几乎没有可能的消息。
看起来像:
public enum first{ONE,TWO,THREE};
public enum second{FOUR,FIVE,SIX};
public enum third{SEVEN,EIGHT,NINE};
public void work(String message){
//Here I want to compare message string to one of the 3 enums
}
是否可以在枚举的一种方法中执行此操作? 或者我应该尝试创建一个,如果出现异常,则尝试另一个,依此类推?
I have a string (which is a message) that I get as input and I need to do one of 4 possible things depending on the string
I know that there is eunm.valueOf() option, but I have 4 different enums, each with few possible messages.
looks something like:
public enum first{ONE,TWO,THREE};
public enum second{FOUR,FIVE,SIX};
public enum third{SEVEN,EIGHT,NINE};
public void work(String message){
//Here I want to compare message string to one of the 3 enums
}
is it possible to do this in one method of the enum?
or should I just try to create one, and if I get an exception try the other and so on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如其他人评论的那样,最好考虑一下您是否真的需要 4 个不同的枚举。
但如果你这样做,你可以让他们实现一个通用接口。然后,您可以将输入字符串映射到适当的枚举成员,并调用其方法来完成您想要的操作。 This假设
您想做的 4 件可能的事情对应于 4 个枚举。如果没有,您也可以为每个枚举成员单独重写该方法,例如
As others have commented, it may be better to think through whether you really need 4 distinct enums.
But if you do, you could have them implement a common interface. Then you can map the input strings to the appropriate enum member, and call its method to accomplish what you want. Something like
This assumes that the 4 possible things you want to do correspond to the 4 enums. If not, you can override the method separately for each and any enum member too, e.g.
Java 中的枚举是成熟的类。个人价值观甚至可以凌驾于满足其需求的行为之上。非常酷。您可以利用这一点来发挥您的优势:
Enumerations in Java are full blown classes. Individual values can even override the behavior to meet their needs. It's pretty cool. You can use this to your advantage:
您可以创建所有这些的地图
You can create a Map of them all
您真正要寻找的是其他枚举的聚合。最简单的方法是创建一个新的枚举,将所有这些选择放入一个新的枚举中。效果如下:
这将更正确地将先前的枚举聚合到单个数据结构中。
What you're really looking for is a aggregation of the other enums. The easiest way to get that is to make a new
enum
that puts all of those choices in a newenum
. Something to this effect:This will more correctly aggregate the previous enums into a single data structure.
即使在评论中给出了奇数/偶数示例,我也不认为多个枚举是这里的方法。我会使用类似的东西(警告,未经测试):
然后您可以使用
valueOf()
查找枚举元素,并使用getType()
找出您的三个元素中的哪一个它所属的类别。Even given your odd/even example in the comments, I don't feel multiple enums are the way to go here. I would use something like (warning, untested):
Then you can use
valueOf()
to look up the enum element, andgetType()
to find out which of your three categories it belongs to.目前尚不完全清楚您要问什么,但也许您想定义字符串和常量之间的映射,如下所示:
It isn't entirely clear what you are asking, but perhaps you want to define a mapping between strings and constants, like this: