tags:

views:

130

answers:

2

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?

+5  A: 

(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.

Jon Skeet
Just a remark, you can use getClasses() or getDeclaredClasses() depending on your needs.
Alexander
@Alexander: I suspect that getDeclaredClasses() is almost always the way to go, so I edited the answer.
Jon Skeet
I retracted my answer because this one is now more general, and sounds like a very sensible approach to me. :-)
Chris Jester-Young
If it's a specialised enum constant you'll need to `getSuperclass`.
Tom Hawtin - tackline
public enum En { X() { public String toString() { return ""; } } ; static { System.err.println(X.getClass().getEnumConstants()); }}
Tom Hawtin - tackline
+1  A: 

obj.getClass().getEnumConstants()

gizmo
getEnumConstants will return the enum 'elements' defined by this class if it is an Enum (see http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getEnumConstants() )
Angelo