关于淘淘商城的BaseServiceImpl,泛型变量T的Class获得

最近在看淘淘商城的源码,分享一下BaseServiceImpl的实现。

封装基本的业务操作实现

public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    private Mapper<T> mapper;

    private Class<T> clazz;

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

    @Override
    public T queryById(Long id) {
        T t = this.mapper.selectByPrimaryKey(id);
        return t;
    }
    ......
}

通过spring注入代理对象

    @Autowired
    private Mapper<T> mapper;

传进来的泛型的Class类型

private Class<T> clazz;

这个泛型变量T的Class是不能直接通过T.class获得的
下面就是如何获得T这个的Class 的操作了

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

一、父类中的this

刚开始看的时候,总以为this指的是BaseServiceImpl这个对象,因为以前讲的子类继承父类之后,创建子类对象的时候,首先会创建子类的父类对象。最后发现原来里面的this一直指的是子类对象,做个试验就知道了。

创建一个父类Person

public class Person{
    private Integer id;
    private String name;
    public Person(Integer id,String name){
        this.id = id;
        this.name = name;
        System.out.println(this);
    }
}

创建一个子类Student

public class Student extends Person{
    public Student(Integer id,String name){
        super(id,name);
    }
}

测试

 public static void main(String[] args){
        new Student(1,"张三");
    }

结果
这里写图片描述

二、关于Class和Type

一个class(A.class)文件被加载进入JVM的时候,会被实例化出一个Class 对象,Class源码如下:

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {

Class类是实现了Type接口,以后的创建 A的对象就会根据 这个Class对象来创建

扫描二维码关注公众号,回复: 2805492 查看本文章

我们常用的方法: 类名.class 和 对象.getClass() 就可以获得这个Class对象,在jdk1.5以后,引入了泛型概念,为了拓展Class功能,就让Class实现了Type接口,Type源代码如下:

/**
 * Type is the common superinterface for all types in the Java
 * programming language. These include raw types, parameterized types,
 * array types, type variables and primitive types.
 *
 * @since 1.5
 */
public interface Type {

parameterized types指的就是泛型

第一步通过子类的Class获得父类的Class对象。
Type type = this.getClass().getGenericSuperclass();

//type为  父类的Class对象
com.fengqu.testClass.BaseServiceImpl<java.lang.String>

第二步 强转
ParameterizedType p = (ParameterizedType) type;

com.fengqu.testClass.BaseServiceImpl<java.lang.String>

// 获取泛型的class, 强转获得泛型变量T的Class
this.clazz = (Class<T>) pType.getActualTypeArguments()[0];

class java.lang.String

猜你喜欢

转载自blog.csdn.net/qq_35986866/article/details/81744228