views:

466

answers:

1

If you have an enum that you are accessing via reflection how would you pass it's value into method.invoke call.

Would it be something like (shown as a static method for simplicity)


    Class enumClazz = Class.forName("mypkg.MyEnum",true,MyClassLoader);
    Class myReflectedClazz = Class.forName("mypkg.MyClass",true,MyClassLoader);
    Field f = enumClazz.getField("MyEnumValue");

    Method m = myReflectedClazz.getMethod("myMethod",enumClazz);
    m.invoke(null,f.get(null));
+1  A: 

You should probably do:

Enum e = Enum.valueOf(enumClazz, "MyEnumValue");

You will get unchecked warnings as you are using raw types but this will compile and run.

Using reflection, you would need to pass an instance to access a Field - however in the case of static methods, you can pass in null to Field's get method as follows:

m.invoke(null,f.get(null));

Also - is myMethod a static method as you are calling this with no instance as well?

oxbow_lakes
He was using the field to try and get enum value. With your code it should be `m.invoke(null, e)`
ChssPly76
Yes, myMethod was static.
joshh
@ChssPly76 - I think you need to read my answer again. There's nowt wrong with it
oxbow_lakes