开发者

How to use a generic factory for generic type without warnings?

I have a factory method like

public static <T> Something<T> create(Class<T> clazz) {
    return new Something<T>(clazz);
}

t开发者_运维问答aking a Class argument. When I use it like in

Something<String> something1 = Something.create(String.class);

everything is fine. But for

Something<List> something2 = Something.create(List.class);

I get a warning I can't get rid of. For whatever I try I get a warning or an error.

Is there anything I could do besides @SuppressWarnings("unchecked")?

Actually, I'd like to get

Something<List<?>> something2 = Something.create(List.class);

which I can't get without two casts and a warning. I'm using eclipse 3.5.2.


@SuppressWarnings("unchecked")
static public <A, B extends A> Class<B> rawcast(Class<A> clazz)
{ 
    return (Class<B>)clazz; 
}

void test()
{
    Class<List<?>> clazz = rawcast(List.class);

    Something<List<?>> something2 = Something.create(clazz);
}


One way is to provide the method with a dummy instance of the class you would like to use for the generic parameter. E.g.:

public static <T> List<T> asList(T a) {
   return new ArrayList<T>();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜