Acquiring generic class type

前端 未结 5 1643
轻奢々
轻奢々 2021-01-02 19:40

Hi is there any way in Java to get staticly generic class type

I have ended up with construct

    List l = new ArrayList&         


        
5条回答
  •  误落风尘
    2021-01-02 20:25

    I'm not sure if you noticed, but in your example you will get java.util.ArrayList class in "c" variable. I'm not sure if this is your point. However if we asume, that yes it is:

    @SuppressWarnings("unchecked")
    Class> c = (Class>) ArrayList.class;
    

    However if you need list, use this:

    @SuppressWarnings("unchecked")
    Class> c = (Class>) List.class;
    

    I added @SuppressWarnings annotation to get rid of warnings. This annotation can be used with any granularity, so you can also flag your local code with it.

    The key idea in this approach is that generics are erasure. There is no information about them in runtime, to above assignments are correct.

提交回复
热议问题