继承中的this的含义及通过反射获取泛型参数

来源:互联网 发布:it维修单 编辑:程序博客网 时间:2024/06/05 02:20

在继承中,如果A类继承了B类,super对应B类,this对应A类。

package cn.test;import java.lang.reflect.ParameterizedType;public class Animal<T> {Class<T> clazz=null;public Animal() {//这里的this.getClass()实际上得到的是子类中的new的类对象,因为是在子类的构造器中调用的父类构造方法,所以父类构造器中的this指的是当前new的子类对象System.out.println(this.getClass().getName());ParameterizedType ptType=(ParameterizedType)this.getClass().getGenericSuperclass();//获取当前new的对象的带有泛型的父类System.out.println(ptType);this.clazz=(Class<T>)ptType.getActualTypeArguments()[0];//获取第一个泛型参数的真实类型(泛型可能有多个)System.out.println("clazz--"+clazz);}}
下面是子类信息:

public class Dog extends Animal<Dog>{public Dog() {super();}public static void main(String[] args) {Dog dog=new Dog();}}
执行子类中的main方法,打印结果如下:

cn.itcast.oa.base.Dog
cn.itcast.oa.base.Animal<cn.itcast.oa.base.Dog>
clazz--class cn.itcast.oa.base.Dog


0 0
原创粉丝点击