Tomáš Zato
Tomáš Zato

Reputation: 53358

Can I pass and use enum as a variable?

I'm working on some debug tools. What I'm trying to do at this moment is to provide tester with a GUI window that will display Enum entries - their names and human readable values. I would like to have the base dialog class as generic as possible, because there are multiple enums to be viewed.

Additionally, some of those enums implement common interface. Eg.

public enum DaysOfTheWeek implements CanBeTranslated { ...

Therefore I tried to build on that. After thinking for a while, I created this variable:

Class<Enum<? extends CanBeTranslated>> entries;

I expected to have access to entries.values() as in DaysOfTheWeek.values but nope, it doesn't seem to work that way. What I wanted to do was:

for(CanBeTranslated entry: myMagicEnumVariable.values()) {
    // display entry in GUI
}

Is there a way to work with abstract (as in "not specific one") enum within a variable? I need to have access to the enum in order to get field names, this is important - if this wasn't the case, I could just use the array of values.

Please also keep in mind that this question is asked from the perspective of

I encountered a very hostile attitude from professional Java developpers when I asked weird question about doing things different for fun, hence this disclaimer.

Upvotes: 1

Views: 1003

Answers (1)

shmosel
shmosel

Reputation: 50776

This should do what you want:

Class<? extends CanBeTranslated> entries = DaysOfTheWeek.class;
for (CanBeTranslated entry : entries.getEnumConstants()) {
    // ...
}

Upvotes: 3

Related Questions