[转载] Java获取泛型T的类型 T.class

参考链接: Java中的抽象

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

 

public class Main{

    public static void main(String[] args)

    {

        Foo<String> foo = new Foo<String>(){};

        // 在类的外部这样获取

        Type type = ((ParameterizedType)foo.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        System.out.println(type);

        // 在类的内部这样获取

        System.out.println(foo.getTClass());

    }

}

 

abstract class Foo<T>{

    public Class<T> getTClass()

    {

        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        return tClass;

    }

输出: 

class java.lang.String

class java.lang.String 

上面的代码不是万能的,只有实例化T的子类才能按上述方法获得T的实际类型,  如果子类没有实例化T,则无法获取T的实际类型;  比如,class Child 并没有实例化T,所以得不到String.class; 

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

 

public class Main{

    public static void main(String[] args){

        //区别在new Child<String>()没有{}匿名类

        Foo<String> foo = new Child<String>();

        // 在类的外部这样获取

        Type type = ((ParameterizedType)foo.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        System.out.println(type);

        // 在类的内部这样获取

        System.out.println(foo.getTClass());

    }

}

 

abstract class Foo<T>{

    public Class<T> getTClass()

    {

        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];

        return tClass;

    }

}

 

class Child<T> extends Foo<T>{

输出: 

Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

    at com.hankcs.Main.main(Main.java:9)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:606) 

有一种解决方式,父类本身不获取泛型的具体类型,仅提供抽象方法,由子类来提供具体的类型 

public abstract class Foo<T> {  

    public abstract Class getEntityClass();  

}  

 

public class Child extends Foo<String> {  

    public Class getEntityClass() {  

        return String.class;  

    }  

}   

对于获取泛型的方法,比较完整的代码如下: 

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

 

public class GenericsUtils {

    /**

     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends

     * GenricManager<Book>

     * 

     * @param clazz The class to introspect

     * @return the first generic declaration, or <code>Object.class</code> if cannot be determined

     */

    public static Class getSuperClassGenricType(Class clazz) {

        return getSuperClassGenricType(clazz, 0);

    }

 

    /**

     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>

     * 

     * @param clazz clazz The class to introspect

     * @param index the Index of the generic ddeclaration,start from 0.

     */

    public static Class getSuperClassGenricType(Class clazz, int index)

            throws IndexOutOfBoundsException {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {

            return Object.class;

        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {

            return Object.class;

        }

        if (!(params[index] instanceof Class)) {

            return Object.class;

        }

        return (Class) params[index];

    }

转载来源:  http://blog.csdn.net/wangjunjun2008/article/details/43970217  http://www.hankcs.com/program/t-class.html  https://www.cnblogs.com/sirab415/p/6133533.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值