Get generic type of java.util.List

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

I have;

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

Is

14条回答
  •  没有蜡笔的小新
    2020-11-22 02:39

    Expanding on Steve K's answer:

    /** 
    * Performs a forced cast.  
    * Returns null if the collection type does not match the items in the list.
    * @param data The list to cast.
    * @param listType The type of list to cast to.
    */
    static  List castListSafe(List data, Class listType){
        List retval = null;
        //This test could be skipped if you trust the callers, but it wouldn't be safe then.
        if(data!=null && !data.isEmpty() && listType.isInstance(data.iterator().next().getClass())) {
            @SuppressWarnings("unchecked")//It's OK, we know List contains the expected type.
            List foo = (List)data;
            return retval;
        }
        return retval;
    }
    Usage:
    
    protected WhateverClass add(List data) {//For fluant useage
        if(data==null) || data.isEmpty(){
           throw new IllegalArgumentException("add() " + data==null?"null":"empty" 
           + " collection");
        }
        Class colType = data.iterator().next().getClass();//Something
        aMethod(castListSafe(data, colType));
    }
    
    aMethod(List foo){
       for(Foo foo: List){
          System.out.println(Foo);
       }
    }
    
    aMethod(List bar){
       for(Bar bar: List){
          System.out.println(Bar);
       }
    }
    

提交回复
热议问题