Jonathan
Jonathan

Reputation: 109

Enum reflection

I tried making this line in reflection but failed to make the EnumTitleAction.SUBTITLE:

new ClassA(EnumB.SUBTITLE, "Test");

How to do this?

I tried already to do this:

Class.forName("net.something.ClassA").getConstructors()[1].newInstance(/*Stuck with EnumB*/, "Test");

But I cant find out how to represent the EnumB part with reflection.

Upvotes: 1

Views: 75

Answers (2)

Pshemo
Pshemo

Reputation: 124215

Aside to Mureinik's answer you can also use Enum.valueOf(Class<T> enumType, String name) so your code can probably look like (you will just need to suppress some compiler warnings)

String enumName = "your.EnumName";
String valueName = "SUBTITLE";
Class<? extends Enum> enumType = (Class<? extends Enum>) Class.forName(enumName);

Enum<?> enumValue = Enum.valueOf(enumType, valueName);

Now you should be able to use this enumValue in your code

Class.forName("net.something.ClassA").getConstructors()[1]
             .newInstance(enumValue, "Test");
//                        ^^^^^^^^^

Just make sure that you will pass correct name of your enum value, otherwise valueOf will throw IllegalArgumentException.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311143

Enum values are objects - just use it like you did in the first snippet:

Class.forName("net.something.ClassA").getConstructors()[1].newInstance
    (EnumB.SUBTITLE, "Test");

Edit:
As per comment below, the problem is getting an enum constant by reflection. The way to go at it is to use Class.getEnumConstants(). If you know SUBTITLES's location in EnumB this is fairly straight forward:

Class.forName("net.something.ClassA").getConstructors()[1].newInstance
    (Class.forName("net.something.EnumB").getEnumConstants()[4], "Test");

But as you may suspect, this coding style is pretty fragile. A better approach would be to find it according to its name:

Class clazz = Class.forName("net.something.EnumB");
Method nameMethod = clazz.getMethod("name");
Object value = null;
Object[] enums = clazz.getEnumConstants();

for (Object o : enums) {
    if (nameMethod.invoke(o).equals("SUBTITLE")) {
        value = o;
        break;
    }
}
Class.forName("net.something.ClassA").getConstructors()[1].newInstance
    (value, "Test");

Upvotes: 1

Related Questions