开发者

Java generics trouble [closed]

开发者 https://www.devze.com 2023-04-07 11:31 出处:网络
It开发者_JAVA技巧9;s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form.
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

精彩评论

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

关注公众号