How do I get a class instance of generic type T?

前端 未结 22 1249
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  迷失自我
    2020-11-21 11:50

    Actually, I suppose you have a field in your class of type T. If there's no field of type T, what's the point of having a generic Type? So, you can simply do an instanceof on that field.

    In my case, I have a

    List items;
    in my class, and I check if the class type is "Locality" by

    if (items.get(0) instanceof Locality) ...
    

    Of course, this only works if the total number of possible classes is limited.

提交回复
热议问题