Java generics trouble [closed]
I'm about to give up on that snippet: I don't grok Java generics... I'm trying to return the value of an enum when getting a System property with that enum name, as in:
enum E { A, B }
...
E mode = GetEnumProperty("mode", E.A);
where GetEnumProperty is:
static <T> T GetEnumProperty(String propName, T extends Enum<T> defaultValue)
{
if (System.getProperty(propName) != null) {
return Enum.valueOf(defaultValue.getClass(), System.getProperty(propName));
} else {
return defaultValue;
}
}
Thanks!
It looks like what you want is this:
public class GenericEnum {
static <T extends Enum<T>> T GetEnumProperty(String propName, T defaultValue)
{
if (System.getProperty(propName) != null) {
return (T)Enum.valueOf(defaultValue.getClass(), System.getProperty(propName));
} else {
return defaultValue;
}
}
Notice the change in how generic type T is specified in the method declaration. You need to declare that the type T extends Enum before you use it in the parameter list.
Also note the cast (T) in the first return statement.
You need some Generics background- this is basic generics here.
Dense, but helpful white-paper - http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
http://download.oracle.com/javase/tutorial/java/generics/index.html
精彩评论