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;
    
    }
  • 相关阅读:
    如何:创建自定义 HTTP 模块
    [转]开源邮件系统
    [转]开源.NET邮件服务器
    [转]文件上传及图片水印
    oracle存储过程学习收集|韩顺平oracle视频教程|
    PLSQL自动输入select * from|附件在cnblogs文件|
    oracle有规律数据触发器实现递增(NC地区分类)|更新一路case简化|
    oracle中的几种循环|转|
    官方解释sqlplus /nolog conn /as sysdba无密码可登陆
    建工项目对账查询引擎sql
  • 原文地址:https://www.cnblogs.com/Yiran583/p/4224103.html
Copyright © 2011-2022 走看看