zoukankan      html  css  js  c++  java
  • 在父类中反射获取泛型类型

      使用Struts2时做CRUD时,每个action都需要写相同重复的代码,于是就想着将这些个代码放到一个父类中,子类直接使用父类中的方法。

      但是由于保存的时候需要传递一个具体的实体,而每个action功能不一样,传递的实体也不一样,于是就想到了反射。

      子类:

    public class UserAction extends BaseAction<User> {}

      父类

    public abstract class BaseAction<T> extends ActionSupport implements RequestAware, ModelDriven<T> {protected Map<String, Object> request;
        protected Long id;
        private Class<T> clazz = null;
    
        public BaseAction() {
            // TODO Auto-generated constructor stub
            ParameterizedType pt = (ParameterizedType) this.getClass()
                    .getGenericSuperclass(); //获取泛型类型数组
            this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; //获取泛型类型
        }
    
        protected T model;
    
        @Override
        public T getModel() { //通过传入不同的泛型类型,获取具体的实例
            try {
                model = clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (id != null) {
                if (model instanceof Department) {
                    model = (T) departmentService.getById(id);
                } else if (model instanceof Role) {
                    model = (T) roleService.getById(id);
                } else if (model instanceof User) {
                    model = (T) userService.getById(id);
                } else if (model instanceof Privilege) {
                    model = (T) privilegeService.getById(id);
                }
            }
            return model;
        }
    
        @Override
        public void setRequest(Map<String, Object> arg0) {
            request = arg0;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        @Resource
        protected IDepartmentService departmentService;
        @Resource
        protected IRoleService roleService;
        @Resource
        protected IUserService userService;
        @Resource
        protected IPrivilegeService privilegeService;
    
    }
  • 相关阅读:
    Karma: 3
    Karma:2. 集成 Karma 和 mocha 进行单元测试
    Android Eclipseproject开发中的常见调试问题(二)android.os.NetworkOnMainThreadException 异常的解决的方法
    CSDN日报20170226——《你离心想事成仅仅差一个计划》
    重装linuxserver简易流程
    移动端 h5开发相关内容总结——CSS篇
    Oracle学习笔记(6)——函数
    Spark学习
    Android教你怎样一步步打造通用适配器
    C语言学习
  • 原文地址:https://www.cnblogs.com/Yiran583/p/4224103.html
Copyright © 2011-2022 走看看