Reputation: 2976
I want to create an Enum editor, which takes an Enum type as its generic. E is a generic type, but restricted to be an Enum type. How can I get the values of the Enum class from the instance e?
public class ComboBoxEnumEditor<E extends Enum<E>>{
public ComboBoxEnumEditor(E e) {
// how to get values of E from e?
// attemp1:
List values = e.getClass().values();
// attemp2:
List values = ((Enum.class)e.getClass()).values();
// attemp3:
List values = ((Enum.class)e.getClass()).values();
// none of the above works...
}
}
Say I have an Enum
public enum Location {
Default( false, EAttributeLocation.MAIN_TABLE_IF_AVAILABLE ),
Main( false, EAttributeLocation.MAIN_TABLE ),
Overflow( false, EAttributeLocation.OVERFLOW_TABLE ),
Separate( false, EAttributeLocation.SEPARATE_TABLE );
......
}
I want my ComboBoxEnumEditor be able to do
{
ComboBoxEnumEditor(new Location());
}
Please help, thanks.
Upvotes: 4
Views: 4890
Reputation: 124275
It looks like you are looking for (but I may be mistaken)
Enum[] values = e.getClass().getEnumConstants();
or as mentioned by @pbabcdefp in this answer (big +1 for him) if you would like to have E[]
instead of Enum[]
E[] values = e.getDeclaringClass().getEnumConstants();
Also based on
...which takes an Enum Class as its generic
your argument should probably be Class<E> clazz
not E e
itself so you could use it with ComboBoxEnumEditor(Location.class);
. In that case you could simply use
E[] values = clazz.getEnumConstants();
Upvotes: 14
Reputation: 9786
Short answer... You can't. Doing this is not valid syntax since you can't instantiate an enum:
ComboBoxEnumEditor(new Location());
Instead, you need to pass the class of your enum and change your method signature for that, e.g.
ComboBoxEnumEditor(Location.class);
Upvotes: 0