java继承后获取泛型类的class并实例化

复制代码
public class Super <T, W> {
    
    T newT() throws IllegalAccessException, InstantiationException {
        final Class<T> classT = this.getClassT();
        return classT.newInstance();
    }

    protected Class<T> getClassT() {
        Type type = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) type;
        // 如果想获取W的class对象这里用1
        Type typeArg = parameterizedType.getActualTypeArguments()[0];
        return (Class<T>) typeArg;
    }
}

public class Sub extends Super<BeanAbc, String> {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Sub sub = new Sub();
        final BeanAbc beanAbc = sub.newT();
        System.out.println(beanAbc);
    }

}

public class BeanAbc {

    private Integer id;
    private String name;

    public BeanAbc() {
        this.id = 1;
        this.name = "ddd";
    }
}

输出:

BeanAbc(id=1, name=ddd)

主要用途:当某些对象的处理逻辑相似的时候,可以使用泛型类将不同的地方抽取出来,这样只要创建多个子类,就可以实现多种不同的业务逻辑。该功能是从mp的思路中学习的。

mybatis plus有个非常实用的类:

复制代码
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T>
相关推荐
weixin199701080161 分钟前
南网商城商品详情页前端性能优化实战
java·前端·性能优化
iPadiPhone4 分钟前
Spring Boot 自动装配原理与 Starter 开发实战
java·spring boot·后端·spring·面试
SuGarSJL5 分钟前
FakeSMTP-2.1.1使用
java·maven
码匠君6 分钟前
首个基于 Spring Boot 4 的正式版发布!Dante Cloud 4.X 新特性全解析
java·spring boot·后端
悟空码字16 分钟前
SpringBoot + 百度地图SDK,打造企业级位置服务中台
java·百度·地图·编程技术·后端开发
weixin1997010801618 分钟前
网易考拉商品详情页前端性能优化实战
java·前端·python·性能优化
Natalia_Portman19 分钟前
springboot整合DolphinDB
java·数据库·spring boot·后端·db
hua8722222 分钟前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
java
不光头强23 分钟前
LinkedList知识点
java