Java基础Java中如何获取一个类中泛型的实际类型

Posted Satire

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java基础Java中如何获取一个类中泛型的实际类型相关的知识,希望对你有一定的参考价值。

泛型的术语

<>: 念做typeof

List<E>: E称为类型参数变量

ArrayList<Integer>: Integer称为实际类型参数

ArrayList<Integer>: 整个ArrayList<Integer>称为参数化类型(对应着java.lang.reflect.ParameterizedType接口)

泛型反射相关API

Type[] getGenericInterfaces():获得当前类实现的泛型接口(参数化类型)

举例1:

1)定义类A,C 接口B

//类B
public interface B{}


//类C
public class C{}


//A实现B,向B传入实际类型参数C
public class A implements B<C>{}

2)测试代码

A a = new A();
Type[] types = a.getClass().getGenericInterfaces();
for (Type type : types) {
          System.out.println(type);//结果是:B<C>
}

Type[] getGenericSuperclass():获得带有泛型的父类

举例2:

1)定义3个类A,B,C

//类B
public class B{}


//类C
public class C{}


//A继承B,向B传入实际类型参数C
public class A extends B<C>{}

2)测试代码

A a = new A();
Type type = a.getClass().getGenericSuperclass();
System.out.println(type);//结果是:B<C>

ParameterizedType:参数化类型接口,Type的子接口

通过上面两个案例可知getGenericInterfaces和getGenericSuperclass可以获取到参数化类型B,并且ParameterizedType是Type的子接口,将Type强转成ParameterizedType。ParameterizedType提供了一个getActualTypeArguments()方法,这个方法可以获取参数化类型中的实际类型参数。

举例3:我们对案例2测试代码进行修改

A a = new A();
//获得带有泛型的父类
Type type = a.getClass().getGenericSuperclass();
System.out.println(type);//结果是:B<C>
//将type强转成Parameterized
ParameterizedType pt = (ParameterizedType )type;
/*得到父类(参数化类型)中的泛型(实际类型参数)的实际类型。
getActualTypeArguments()返回一个Type数组,之所以返回Type数组,是因为一个类上有可能出现多个泛型,比如:Map<Integer,String>
*/
Type [] actualTypes = pt.getActualTypeArguments();
System.out.println(actualTypes[0]);//结果:C

获取接口泛型的实际类型参数做法跟上面代码差不多,只需要把

Type type = a.getClass().getGenericSuperclass(),改成 Type type = a.getClass().getGenericInterfaces()就可以了。

public BasicAction(){

        try {

            //获取子类字节码文件对象,this代表的是子类对象。
            Class clazz = this.getClass();

            //获取子类所属接口的参数化类型,cn.xxx.xxx.BasicAction<cn.xxx.xxx.Standard>
            Type type = clazz.getGenericSuperclass();

            //因为type是顶级接口没有定义任何方法,所以需要强转为子接口ParameterizedType
            ParameterizedType parameterizedType = (ParameterizedType) type;

            //通过子接口定义的getActualTypeArguments方法获取到实际参数类型,<cn.xxx.xxx.Standard>
            //返回参数为数组,因为Java中接口可以多实现
            Type[] types = parameterizedType.getActualTypeArguments();

            //获取数组中的实际参数类型
            Class clzz = (Class) types[0];

            //通过实际参数类型获取实际参数类型的实例
            model = (T) clzz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

以上是关于Java基础Java中如何获取一个类中泛型的实际类型的主要内容,如果未能解决你的问题,请参考以下文章

Java中的泛型的问题?

java中泛型List问题

java如何获得泛型中的类

java中啥叫泛型??

Java泛型的设计

Java中泛型的深入理解