开发者

Java generics trouble [closed]

It开发者_JAVA技巧9;s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜