我有;

List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();

是否有(简单)方法检索列表的泛型类型?


当前回答

一个小的帮助方法:

/**
 * Get type of collection field.
 *
 * @param aClass A class containing collection.
 * @param collectionName A collection field name.
 */
@SneakyThrows
public static Class<?> getCollectionType(Class<?> aClass, String collectionName) {
  Field field = aClass.getDeclaredField(collectionName);
  ParameterizedType genericType = (ParameterizedType) field.getGenericType();
  return (Class<?>) genericType.getActualTypeArguments()[0];
}

其他回答

使用反射来获取这些字段,然后你可以做:Field。genericType来获取包含generic信息的类型。

扩展Steve K的回答:

/** 
* 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 <T> List<? super T> castListSafe(List<?> data, Class<T> listType){
    List<T> 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<T> contains the expected type.
        List<T> foo = (List<T>)data;
        retval=foo;
    }
    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> foo){
   for(Foo foo: List){
      System.out.println(Foo);
   }
}

aMethod(List<Bar> bar){
   for(Bar bar: List){
      System.out.println(Bar);
   }
}

简单的回答是:不。

这可能是复制品,现在找不到合适的。

Java使用类型擦除,这意味着在运行时两个对象是等价的。编译器知道列表包含整数或字符串,因此可以维护类型安全的环境。这些信息在运行时丢失(以对象实例为基础),并且列表只包含“对象”。

你可以找到一些关于类的信息,它可能被参数化的类型,但通常这只是任何扩展“对象”的东西,即任何东西。如果将类型定义为

class <A extends MyClass> AClass {....}

class将只包含参数A受MyClass限制的事实,但除此之外,没有办法告诉它。

正如其他人所说,唯一正确的答案是否定的,该类型已被删除。

如果列表的元素数目非零,则可以研究第一个元素的类型(例如,使用它的getClass方法)。这不会告诉您列表的泛型类型,但可以合理地假设泛型类型是列表中类型的某个超类。

我不提倡这种方法,但在遇到困难时,它可能会有用。

查找一个字段的泛型类型:

((Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]).getSimpleName()