Java: how do I get a class literal from a generic

2018-12-31 19:08发布

Typically, I've seen people use the class literal like this:

Class<Foo> cls = Foo.class;

But what if the type is generic, e.g. List? This works fine, but has a warning since List should be parameterized:

Class<List> cls = List.class

So why not add a <?>? Well, this causes a type mismatch error:

Class<List<?>> cls = List.class

I figured something like this would work, but this is just a plain ol' syntax error:

Class<List<Foo>> cls = List<Foo>.class

How can I get a Class<List<Foo>> statically, e.g. using the class literal?

I could use @SuppressWarnings("unchecked") to get rid of the warnings caused by the non-parameterized use of List in the first example, Class<List> cls = List.class, but I'd rather not.

Any suggestions?

7条回答
旧人旧事旧时光
2楼-- · 2018-12-31 19:40

You can manage it with a double cast :

@SuppressWarnings("unchecked") Class<List<Foo>> cls = (Class<List<Foo>>)(Object)List.class

查看更多
登录 后发表回答