I have fairly simple problem.
I have a variable of type java.lang.reflect.Type and I want to do two different things to it in case its holds class or enumeration. I can fairly simple check if the varaible is enum by simply asking .isEnum()
. However to call the specific enumeration methods I need to cast this variable to be enumeration. Here is some code for illustration. I know it does not make much of a sence, but its just for the cast illustration:
public class TestClass {
public static String text = "MySampleTextClass.";
}
public enum TestEnum {
MySampleText
}
public class Tester {
public static Object retrieveValue (java.lang.reflect.Type myVar, String enumStringValue) {
String enumStringValue = "MySampleText";
// the variable is enum!!!
if (myVar.isEnum()) {
return (Enum myVar).valueOf(enumStringValue);
}
// the variable is class!!!
else {
return myVar.getClass().getSimpleName();
}
}
}
I tried casts like
(java.lang.Enum myVar).valueOf(enumString);
or
(java.lang.Enum<?> myVar).valueOf(enumString);
but I can't make it work.
Any ideas?
Use the static method valueOf
that is declared in the abstract class Enum
:
Class clazz = (Class) myVar;
if (clazz.isEnum()) {
return Enum.valueOf(clazz, enumStringValue);
}
But ... a cast to Class is necessary as java.lang.reflect.Type is just a marker interface. Additionally, you must cast to the raw type Class to make it work. There are many runtime traps you can get into.
Overall, it's very uncummon to have such a requirement. Why do you have to use reflection for retrieving an enum value for which you even do not know the type?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments