Acquiring generic class type

前端 未结 5 1604
轻奢々
轻奢々 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:34

    Since all List classes actually correspond to the same class at runtime, you could do this:

    Class> c 
        = (Class>) List.class;
    

    But for some reason, Java doesn't like it. Tried it with String:

    Laj.java:9: inconvertible types
    found   : java.lang.Class
    required: java.lang.Class>
    Class> c = (Class>) List.class;
    

    Well, let's fool it then:

    Class> c = 
       (Class>) (Class) List.class;
    

    It's silly, but it works. It produces an "unchecked" warning, but so does your example. Note that it doesn't result in the same class as your example, though. Your example returns the actual class of the object, namely ArrayList. This one returns List, obviously.

提交回复
热议问题