Can I call .class on a generic type in Java?

前端 未结 3 1141
[愿得一人]
[愿得一人] 2021-01-02 00:40

I was wondering if there is a way in Java to do something like

Class c = List.class;
Class c2 = List.class;

I nee

3条回答
  •  盖世英雄少女心
    2021-01-02 01:13

    You can't to it quite like this, but you can achieve your overall aim using the same approach as Guice does with TypeLiteral. If you're using Guice already, I suggest you use that directly - otherwise, you might want to create your own similar class.

    Essentially the idea is that subclasses of a generic type which specify type arguments directly retain that information. So you write something like:

    TypeLiteral literal = new TypeLiteral>() {};
    

    Then you can use literal.getClass().getGenericSuperclass() and get the type arguments from that. TypeLiteral itself doesn't need to have any interesting code (I don't know whether it does have anything in Guice, for other reasons).

提交回复
热议问题