I know I can get the public static members of a class by doing something like:
我知道我可以通过以下方式获得类的公共静态成员:
obj.getClass().getFields()
but this doesn't get me the enums. I'd like to be able to get them from the Class object returned by the getClass method. Any ideas?
但是这并不能让我知道这些内容。我希望能够从getClass方法返回的Class对象中获取它们。有任何想法吗?
2 个解决方案
#1
6
(Turned into a community wiki as it looks like there's scope for a fair amount of expansion, e.g. to include tackline's comments. No sense in me just transcribing comments when everyone could be expanding it.)
(转变为社区维基,因为它看起来有相当大的扩展范围,例如包括攻击线的评论。当我没有意义只是在每个人都可以扩展它时转录评论。)
Do you mean enums nested within a top-level class? If so, use Class.getDeclaredClasses()
and iterate through the results seeing if any of the nested classes are enums. The simplest way of testing each nested class is to use Class.isEnum()
; if you want to iterate through the values within the enum then Class.getEnumConstants()
is the way to go.
你的意思是嵌套在*类中的枚举吗?如果是这样,请使用Class.getDeclaredClasses()并遍历结果,查看是否有任何嵌套类是枚举。测试每个嵌套类的最简单方法是使用Class.isEnum();如果你想遍历枚举中的值,那么Class.getEnumConstants()就是你要走的路。
#2
1
obj.getClass().getEnumConstants()
#1
6
(Turned into a community wiki as it looks like there's scope for a fair amount of expansion, e.g. to include tackline's comments. No sense in me just transcribing comments when everyone could be expanding it.)
(转变为社区维基,因为它看起来有相当大的扩展范围,例如包括攻击线的评论。当我没有意义只是在每个人都可以扩展它时转录评论。)
Do you mean enums nested within a top-level class? If so, use Class.getDeclaredClasses()
and iterate through the results seeing if any of the nested classes are enums. The simplest way of testing each nested class is to use Class.isEnum()
; if you want to iterate through the values within the enum then Class.getEnumConstants()
is the way to go.
你的意思是嵌套在*类中的枚举吗?如果是这样,请使用Class.getDeclaredClasses()并遍历结果,查看是否有任何嵌套类是枚举。测试每个嵌套类的最简单方法是使用Class.isEnum();如果你想遍历枚举中的值,那么Class.getEnumConstants()就是你要走的路。
#2
1
obj.getClass().getEnumConstants()