开发者

How to instantiate generic variable like Class<Foo<T>>?

开发者 https://www.devze.com 2022-12-16 19:17 出处:网络
I need to instantiate generic variable like Class>. For example, Class<? extends List<String>> = ...

I need to instantiate generic variable like Class>. For example,

Class<? extends List<String>> = ...

Variant 1:

Class<? extends List<String>> clazz = LinkedList.class;

don't work - "Incomp开发者_如何学Goatible types".

Variant 2:

Class<? extends List> clazz = LinkedList.class;

work, but in this case List is a raw type - not good.

How to instantiate such variables?


There is not really a point in having Class<List<String>>, since it would be equivalent to Class<List<Integer>> (both being a reference to the raw List due to erasure).

Having said that, if your intention is to represent the List<String> type, this is possible, see TypeLiteral of Google Guice.

TypeLiteral<List<String>> type = new TypeLiteral<List<String>>() {};
System.out.println(type.getType()); //should print List<String>

The mechanism that makes it possible is reflection on static type declarations, in either class definition (class X extends Foo<Y>, Y is available through reflection, it is preserved in the bytecode), method definitions, etc. TypeLiteral uses the former, you may notice that it creates a brand new class, so the net effect is that your type parameter gets preserved. It's a nice workaround when you are really fighting against erasure.


You can't do it properly. Either use the raw type or use an unsafe cast.


List<String> myList = new ArrayList<String>();
Class<? extends List<String>> var = (Class<? extends List<String>>)myList.getClass();


You can write:

    class ListString extends java.util.LinkedList<String> { }
    Class<? extends java.util.List<String>> clazz = ListString.class;

However, given what Class represents, there isn't that much point. You are better off avoiding reflection wherever possible.

0

精彩评论

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