简体   繁体   中英

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.

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");

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM