Reputation: 151
My enum types-
public enum Foo {A, B, C}
And
public enum Bar {A("aaa"), B("bbb"), C("ccc")}
All I have at runtime is the enum class name i.e. "Foo"
I do this -
Class<?> c = Class.forName(getClassName()) // local function
Using Arrays.asList(c.getEnumConstants())
gets me -
Foo -
[A, B, C]
Bar -
[aaa, bbb, ccc]
I also want [A, B, C]
when evaluating Bar
.
.values()
is what I want but how do I get to it dynamically without any explicit casting?
Many thanks for any replies.
List<? extends Enum<?>> enums = (List<? extends Enum<?>>) Arrays.asList(c.getEnumConstants());
for (Enum<?> e: enums) {
System.err.println("e.name: " + e.name());
}
Upvotes: 2
Views: 8089
Reputation: 65879
I suspect your Arrays.asList(c.getEnumConstants())
is actually working correctly. What you are seeing when you print the array out is a list of the toString()
results of Bar
which become [aaa, bbb, ccc]
.
Try something like:
for (Bar b : Bar.class.getEnumConstants()) {
System.out.println(b.name() + "(\"" + b.toString() + "\")");
}
You should see what I mean.
If you have an enum
that defines its own toString()
you could try wrapping it:
static class EnumNamer<T extends Enum<T>> {
final T he;
public EnumNamer(T he) {
this.he = he;
}
@Override
public String toString() {
return he.name();
}
}
public void test() {
System.out.println("Hello");
for (Bar b : Bar.class.getEnumConstants()) {
System.out.println(b.name() + "(\"" + b.toString() + "\")");
EnumNamer<Bar> en = new EnumNamer<>(b);
System.out.println(en + "(\"" + en.toString() + "\")");
}
}
Now you've clarified a few points - this works for me:
// This cast should be OK so long as we KNOW its an enum.
Class<Enum> c = (Class<Enum>)Class.forName(Bar.class.getName());
for (Enum e : c.getEnumConstants()) {
EnumNamer en = new EnumNamer(e);
System.out.println(en + "(\"" + en.toString() + "\")");
}
Upvotes: 3
Reputation: 1495
For Bar
You can use the following code while retrieving the constants:
List<Bar> list = Arrays.asList(c.getEnumConstants());
List<String> list1 = new ArrayList<String>();
for (Bar b : list)
{
list1.add(b.name());
}
System.out.println(list1);
Upvotes: 0