Get generic type of java.util.List

后端 未结 14 2301
广开言路
广开言路 2020-11-22 02:06

I have;

List stringList = new ArrayList();
List integerList = new ArrayList();

Is

相关标签:
14条回答
  • 2020-11-22 02:43

    Had the same problem, but I used instanceof instead. Did it this way:

    List<Object> listCheck = (List<Object>)(Object) stringList;
        if (!listCheck.isEmpty()) {
           if (listCheck.get(0) instanceof String) {
               System.out.println("List type is String");
           }
           if (listCheck.get(0) instanceof Integer) {
               System.out.println("List type is Integer");
           }
        }
    }
    

    This involves using unchecked casts so only do this when you know it is a list, and what type it can be.

    0 讨论(0)
  • 2020-11-22 02:45

    The type is erased so you will not be able to. See http://en.wikipedia.org/wiki/Type_erasure and http://en.wikipedia.org/wiki/Generics_in_Java#Type_erasure

    0 讨论(0)
提交回复
热议问题