pass reflected enum to method.invoke java
-
16-09-2019 - |
Question
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));
Solution
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?
OTHER TIPS
You have an enum definition:
public enum MyEnum {
MY_SAMPLE_ENUM
}
And a class which has a method that has an enum parameter:
public class SampleClass {
public static void myMethod(MyEnum myEnumParam) {
// some logic here
}
}
Invoke SampleClass.myMethod(MyEnum.MY_SAMPLE_ENUM)
by reflection:
Class clazzMyEnum= Class.forName("mypkg.MyEnum", true, myClassLoader);
Enum enum_MY_SAMPLE_ENUM = Enum.valueOf(clazzMyEnum, "MY_SAMPLE_ENUM");
Class clazzSampleClass = Class.forName("mypkg.SampleClass", true, myClassLoader);
Method methodMyMethod = clazzSampleClass.getMethod("myMethod", clazzMyEnum);
methodMyMethod.invoke(null, enum_MY_SAMPLE_ENUM);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow