Java -- 获取实现接口的泛型的参数化类型和实际类型参数

前言:在向上抽取功能时可能会有需要获取到实现接口的实际泛型参数类型这样的需求,分享一下自己实现的方法

一、Java 代码

直接上代码,代码上有注释,对API做了相应的解释。

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();
        }
    }

猜你喜欢

转载自blog.csdn.net/m0_37602117/article/details/79785697