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;
    
    }
  • 相关阅读:
    python爬取图片
    TensorFlow学习系列(四):minist实例--卷积神经网络
    TensorFlow学习系列(四):minist实例--用简单的神经网络训练和测试
    TensorFlow学习系列(三):实例数据下载和读取
    TensorFlow学习系列(二):入门起步
    TensorFlow学习系列(一):安装调试
    Anaconda安装
    screen的安装和使用
    YII 使用mysql语句查询
    YII 返回值为JSON格式
  • 原文地址:https://www.cnblogs.com/Yiran583/p/4224103.html
Copyright © 2011-2022 走看看