是否可以迭代多个枚举类?
我有三个枚举类。我想以某种方式将它们放入一个数组中,循环遍历该数组并在每个枚举类中调用相同的方法。这在Java中可能吗?
在我看来,你不能将枚举类型放置在数组结构中(除非我错过了如何放置)。
谢谢。
I have three enum classes. I want to somehow put these in an array, loop through the array and call the same method in each enum class. Is this possible in Java?
It seems to me you can't place enum types in an array structure (unless i've missed how).
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让每个枚举类型实现一个通用接口,其中包含您想要调用的通用方法。现在,您可以在迭代时将每个枚举强制转换为该公共接口并调用该方法。另请参阅 EnumSet
Let each enum type implement a common interface that has the common method that you want into invoke. You can now cast each enum, while iterating, to this common interface and call the method. Also look at EnumSet
下面是一个包含 2 个枚举并使用反射的示例:
您可以将类放入数组中并使用反射为每个枚举常量调用方法:
Here is an example with 2 enums and using reflection:
You can put the classes into an array and use reflection to call a method for each enum constant:
如果枚举类是指三个不同的枚举,每个枚举都有自己的元素,那么您可以使用
Enum[]
类型的数组。如果您指的是单个枚举中的三个项目,我们将其称为enum X
,那么您可以将它们放入X[]
类型的数组中。如果您尝试在每个函数上调用标准枚举函数,那么您应该已准备就绪。如果您需要对它们调用自己的函数,并且要使用
Enum[]
数组,则需要使用反射或让它们全部实现相同的接口。If, by enum classes, you mean three different enums, each with their own elements, then you can use an array of type
Enum[]
. If you mean three items from a single enum, let's call itenum X
, then you would put them in an array of typeX[]
.If you are trying to call a standard Enum function on each one, then you should be all set. If you need to call your own function on them, and are going with an array of
Enum[]
, you'll either need to use reflection or have them all implement the same interface.