如何获取泛型类型T的类实例

时间:2010-08-09 06:58:46

标签: java generics

我有一个泛型类Foo<T>。在Foo的方法中,我想获取类型为T的类实例,但我无法调用T.class

使用T.class解决问题的首选方式是什么?

22 个答案:

答案 0 :(得分:509)

简而言之,没有办法在Java中找出泛型类型参数的运行时类型。我建议在Java Tutorial中阅读有关类型擦除的章节以获取更多详细信息。

一种流行的解决方案是将类型参数的Class传递给泛型类型的构造函数,例如

class Foo<T> {
    final Class<T> typeParameterClass;

    public Foo(Class<T> typeParameterClass) {
        this.typeParameterClass = typeParameterClass;
    }

    public void bar() {
        // you can access the typeParameterClass here and do whatever you like
    }
}

答案 1 :(得分:199)

我一直在寻找一种方法来自己完成这项工作,而无需在类路径中添加额外的依赖项。经过一些调查后,我发现 是可能的,只要你有一个通用的超类型。这对我来说没关系,因为我正在使用具有通用图层超类型的DAO图层。如果这适合你的情况那么这是最好的方法恕我直言。

我遇到的大多数泛型用例都有某种通用的超类型,例如: List<T>的{​​{1}}或ArrayList<T>的{​​{1}}等。

纯Java解决方案

文章 Accessing generic types at runtime in Java 解释了如何使用纯Java来实现它。

Spring解决方案

我的项目正在使用Spring,这更好,因为Spring有一个方便的实用工具方法来查找类型。这对我来说是最好的方法,因为它看起来最好。我想如果你没有使用Spring,你可以编写自己的实用方法。

GenericDAO<T>

答案 2 :(得分:88)

但是有一个小漏洞:如果你将Foo类定义为抽象。 这意味着你必须将你的类实例化为:

Foo<MyType> myFoo = new Foo<MyType>(){};

(注意最后的双括号。)

现在您可以在运行时检索T的类型:

Type mySuperclass = myFoo.getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];

但请注意,mySuperclass必须是实际定义T的最终类型的类定义的超类。

它也不是很优雅,但你必须在代码中决定是否更喜欢new Foo<MyType>(){}new Foo<MyType>(MyType.class);


例如:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.NoSuchElementException;

/**
 * Captures and silently ignores stack exceptions upon popping.
 */
public abstract class SilentStack<E> extends ArrayDeque<E> {
  public E pop() {
    try {
      return super.pop();
    }
    catch( NoSuchElementException nsee ) {
      return create();
    }
  }

  public E create() {
    try {
      Type sooper = getClass().getGenericSuperclass();
      Type t = ((ParameterizedType)sooper).getActualTypeArguments()[ 0 ];

      return (E)(Class.forName( t.toString() ).newInstance());
    }
    catch( Exception e ) {
      return null;
    }
  }
}

然后:

public class Main {
    // Note the braces...
    private Deque<String> stack = new SilentStack<String>(){};

    public static void main( String args[] ) {
      // Returns a new instance of String.
      String s = stack.pop();
      System.out.printf( "s = '%s'\n", s );
    }
}

答案 3 :(得分:34)

标准方法/变通方法/解决方案是将class对象添加到构造函数中,例如:

 public class Foo<T> {

    private Class<T> type;
    public Foo(Class<T> type) {
      this.type = type;
    }

    public Class<T> getType() {
      return type;
    }

    public T newInstance() {
      return type.newInstance();
    }
 }

答案 4 :(得分:17)

想象一下,你有一个通用的抽象超类:

public abstract class Foo<? extends T> {}

然后你有了第二个类,它扩展了Foo,扩展了T:

public class Second extends Foo<Bar> {}

您可以通过选择Bar.class(来自bert bruynooghe答案)并使用Type实例推断它来获取Foo类中的类Class

Type mySuperclass = myFoo.getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
//Parse it as String
String className = tType.toString().split(" ")[1];
Class clazz = Class.forName(className);

您必须注意此操作并不理想,因此最好缓存计算值以避免对此进行多次计算。其中一个典型用途是通用DAO实现。

最终实施:

public abstract class Foo<T> {

    private Class<T> inferedClass;

    public Class<T> getGenericClass(){
        if(inferedClass == null){
            Type mySuperclass = getClass().getGenericSuperclass();
            Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
            String className = tType.toString().split(" ")[1];
            inferedClass = Class.forName(className);
        }
        return inferedClass;
    }
}

从其他函数的Foo类或Bar类调用时,返回的值为Bar.class。

答案 5 :(得分:13)

这是一个有效的解决方案:

@SuppressWarnings("unchecked")
private Class<T> getGenericTypeClass() {
    try {
        String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
        Class<?> clazz = Class.forName(className);
        return (Class<T>) clazz;
    } catch (Exception e) {
        throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
    }
} 

注意: 只能用作超类

  1. 必须使用类型化类(Child extends Generic<Integer>
  2. 进行扩展

    <强> OR

    1. 必须创建为匿名实施(new Generic<Integer>() {};

答案 6 :(得分:10)

由于类型擦除,你无法做到这一点。另请参阅Stack Overflow问题 Java generics - type erasure - when and what happens

答案 7 :(得分:9)

我在抽象泛型类中遇到过这个问题。在这种特殊情况下,解决方案更简单:

abstract class Foo<T> {
    abstract Class<T> getTClass();
    //...
}

以及后来的派生类:

class Bar extends Foo<Whatever> {
    @Override
    Class<T> getTClass() {
        return Whatever.class;
    }
}

答案 8 :(得分:8)

比其他人建议的类更好的路径是传入一个对象,该对象可以执行您对该类所做的操作,例如,创建一个新实例。

interface Factory<T> {
  T apply();
}

<T> void List<T> make10(Factory<T> factory) {
  List<T> result = new ArrayList<T>();
  for (int a = 0; a < 10; a++)
    result.add(factory.apply());
  return result;
}

class FooFactory<T> implements Factory<Foo<T>> {
  public Foo<T> apply() {
    return new Foo<T>();
  }
}

List<Foo<Integer>> foos = make10(new FooFactory<Integer>());

答案 9 :(得分:5)

我有一个(丑陋但有效)解决这个问题的方法,我最近用过:

import java.lang.reflect.TypeVariable;


public static <T> Class<T> getGenericClass()
{
    __<T> ins = new __<T>();
    TypeVariable<?>[] cls = ins.getClass().getTypeParameters(); 

    return (Class<T>)cls[0].getClass();
}

private final class __<T> // generic helper class which does only provide type information
{
    private __()
    {
    }
}

答案 10 :(得分:4)

有可能:

class Foo<T> {
  Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(Foo.class, this.getClass()).get(0);
}

您需要svn/trunk/dao/src/main/java/com/googlecode/genericdao/dao/ DAOUtil.java中的两个功能。

有关详细说明,请参阅 Reflecting generics

答案 11 :(得分:4)

我假设,由于您有一个通用类,因此您将拥有一个像这样的变量:

private T t;

(此变量需要在构造函数中采用一个值)

在这种情况下,您可以简单地创建以下方法:

Class<T> getClassOfInstance()
{
    return (Class<T>) t.getClass();
}

希望有帮助!

答案 12 :(得分:3)

我找到了一种通用且简单的方法。在我的课程中,我创建了一个方法,根据它在类定义中的位置返回泛型类型。让我们假设一个这样的类定义:

public class MyClass<A, B, C> {

}

现在让我们创建一些属性来保存类型:

public class MyClass<A, B, C> {

    private Class<A> aType;

    private Class<B> bType;

    private Class<C> cType;

// Getters and setters (not necessary if you are going to use them internally)

    } 

然后,您可以创建一个泛型方法,该方法根据泛型定义的索引返回类型:

   /**
     * Returns a {@link Type} object to identify generic types
     * @return type
     */
    private Type getGenericClassType(int index) {
        // To make it use generics without supplying the class type
        Type type = getClass().getGenericSuperclass();

        while (!(type instanceof ParameterizedType)) {
            if (type instanceof ParameterizedType) {
                type = ((Class<?>) ((ParameterizedType) type).getRawType()).getGenericSuperclass();
            } else {
                type = ((Class<?>) type).getGenericSuperclass();
            }
        }

        return ((ParameterizedType) type).getActualTypeArguments()[index];
    }

最后,在构造函数中,只需调用方法并为每种类型发送索引。完整的代码应如下所示:

public class MyClass<A, B, C> {

    private Class<A> aType;

    private Class<B> bType;

    private Class<C> cType;


    public MyClass() {
      this.aType = (Class<A>) getGenericClassType(0);
      this.bType = (Class<B>) getGenericClassType(1);
      this.cType = (Class<C>) getGenericClassType(2);
    }

   /**
     * Returns a {@link Type} object to identify generic types
     * @return type
     */
    private Type getGenericClassType(int index) {

        Type type = getClass().getGenericSuperclass();

        while (!(type instanceof ParameterizedType)) {
            if (type instanceof ParameterizedType) {
                type = ((Class<?>) ((ParameterizedType) type).getRawType()).getGenericSuperclass();
            } else {
                type = ((Class<?>) type).getGenericSuperclass();
            }
        }

        return ((ParameterizedType) type).getActualTypeArguments()[index];
    }
}

答案 13 :(得分:2)

正如其他答案所解释的那样,要使用这种ParameterizedType方法,你需要扩展类,但这似乎是额外的工作来创建一个扩展它的全新类......

因此,使类抽象它会强制您扩展它,从而满足子类化要求。 (使用lombok&#39; @Getter)。

@Getter
public abstract class ConfigurationDefinition<T> {

    private Class<T> type;
    ...

    public ConfigurationDefinition(...) {
        this.type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        ...
    }
}

现在扩展它而不定义新类。 (注意最后的{} ...已扩展,但不要覆盖任何内容 - 除非您愿意)。

private ConfigurationDefinition<String> myConfigA = new ConfigurationDefinition<String>(...){};
private ConfigurationDefinition<File> myConfigB = new ConfigurationDefinition<File>(...){};
...
Class stringType = myConfigA.getType();
Class fileType = myConfigB.getType();

答案 14 :(得分:1)

   public <T> T yourMethodSignature(Class<T> type) {

        // get some object and check the type match the given type
        Object result = ...            

        if (type.isAssignableFrom(result.getClass())) {
            return (T)result;
        } else {
            // handle the error
        }
   }

答案 15 :(得分:1)

如果要扩展或实现使用泛型的任何类/接口,您可以获得父类/接口的通用类型,而无需修改任何现有的类/接口。

可能有三种可能性,

案例1 当您的类扩展使用泛型的类

public class TestGenerics {
    public static void main(String[] args) {
        Type type = TestMySuperGenericType.class.getGenericSuperclass();
        Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
        for(Type gType : gTypes){
            System.out.println("Generic type:"+gType.toString());
        }
    }
}

class GenericClass<T> {
    public void print(T obj){};
}

class TestMySuperGenericType extends GenericClass<Integer> {
}

案例2 当您的类正在实现使用Generics

的接口时
public class TestGenerics {
    public static void main(String[] args) {
        Type[] interfaces = TestMySuperGenericType.class.getGenericInterfaces();
        for(Type type : interfaces){
            Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
            for(Type gType : gTypes){
                System.out.println("Generic type:"+gType.toString());
            }
        }
    }
}

interface GenericClass<T> {
    public void print(T obj);
}

class TestMySuperGenericType implements GenericClass<Integer> {
    public void print(Integer obj){}
}

案例3 当您的界面扩展使用Generics

的界面时
public class TestGenerics {
    public static void main(String[] args) {
        Type[] interfaces = TestMySuperGenericType.class.getGenericInterfaces();
        for(Type type : interfaces){
            Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
            for(Type gType : gTypes){
                System.out.println("Generic type:"+gType.toString());
            }
        }
    }
}

interface GenericClass<T> {
    public void print(T obj);
}

interface TestMySuperGenericType extends GenericClass<Integer> {
}

答案 16 :(得分:1)

这很简单。 如果您需要来自同一班级:

Class clazz = this.getClass();
ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
try {
        Class typeClass = Class.forName( parameterizedType.getActualTypeArguments()[0].getTypeName() );
        // You have the instance of type 'T' in typeClass variable

        System.out.println( "Class instance name: "+  typeClass.getName() );
    } catch (ClassNotFoundException e) {
        System.out.println( "ClassNotFound!! Something wrong! "+ e.getMessage() );
    }

答案 17 :(得分:0)

实际上,我想你的T类中有一个字段。如果没有T类字段,那么有一个泛型类型有什么意义呢?因此,您只需在该字段上执行instanceof即可。

在我的情况下,我的课程中有一个

List<T> items;
,我通过

检查班级类型是否为“地点”
if (items.get(0) instanceof Locality) ...

当然,这只适用于可能类别总数有限的情况。

答案 18 :(得分:0)

这个问题很旧,但现在最好的方法是使用Google Gson

获取自定义viewModel的示例。

Class<CustomViewModel<String>> clazz = new GenericClass<CustomViewModel<String>>().getRawType();
CustomViewModel<String> viewModel = viewModelProvider.get(clazz);

通用类型类

class GenericClass<T>(private val rawType: Class<*>) {

    constructor():this(`$Gson$Types`.getRawType(object : TypeToken<T>() {}.getType()))

    fun getRawType(): Class<T> {
        return rawType as Class<T>
    }
}

答案 19 :(得分:0)

我想将T.class传递给使用泛型的方法

方法 readFile 读取由具有全路径的fileName指定的.csv文件。可能存在具有不同内容的csv文件,因此我需要传递模型文件类,以便可以获取适当的对象。因为这是读取csv文件,所以我想以一种通用的方式来做。由于某种原因或其他原因,以上解决方案均不适用于我。我需要用 Class<? extends T> type以使其正常运行。我使用opencsv库来解析CSV文件。

private <T>List<T> readFile(String fileName, Class<? extends T> type) {

    List<T> dataList = new ArrayList<T>();
    try {
        File file = new File(fileName);

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        CSVReader csvReader = new CSVReader(headerReader);
        // create csv bean reader
        CsvToBean<T> csvToBean = new CsvToBeanBuilder(reader)
                .withType(type)
                .withIgnoreLeadingWhiteSpace(true)
                .build();

        dataList = csvToBean.parse();
    }
    catch (Exception ex) {
        logger.error("Error: ", ex);
    }

    return dataList;
}

这就是readFile方法的调用方式

List<RigSurfaceCSV> rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);

答案 20 :(得分:0)

许多人不知道这个技巧!实际上,我今天才发现它!它像梦一样运作!只需查看以下示例:

public static void main(String[] args) {
    Date d=new Date();  //Or anything you want!
    printMethods(i);
}

public static <T> void printMethods(T t){
    Class<T> clazz= (Class<T>) t.getClass(); // There you go!
    for ( Method m : clazz.getMethods()){
        System.out.println( m.getName() );
    }
}

答案 21 :(得分:-4)

我正在使用解决方法:

{=SUM(ABS(H2:H5))}
相关问题