Suppose I have a method
public <T extends Enum<T>> Enum<T> getEnumValue(String string, ??)
And another method, in a different class,
public T method(String string)
...
getEnumValue(string, ??)
What would I pass from method 2 as the argument to method 1 so that I can get the enum value, ie in my fantasy world I could just do:
method 2:
getEnumValue(string, T.class)
method 1:
getEnumValue(String string, Class<T> clazz)
return Enum.valueOf(clazz, string)
There is no way to do this due to type erasure. You must pass the explicit Class<T>
, or enough information to recover it (eg the name as a String
that you can pass to Class.forName
, or an instance of T
).
EnumClass.getEnumConstants()
It's in java.lang.Class
not java.lang.Enum
. Use your EnumClass.VALUE.cardinal()
to index this array.
If you insist to call on String
name, you can do
EnumClass.getEnumConstants()[0].valueOf(stringValue)
This is to call static method on instance and you probably receive compiler warning but it works.
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.