首页 > 其他 > 详细

泛型的反射

时间:2016-02-20 01:50:47      阅读:167      评论:0      收藏:0      [点我收藏+]
package cn.itcast.oa.base;

import java.lang.reflect.ParameterizedType;

import javax.annotation.Resource;

import cn.itcast.oa.service.DepartmentService;
import cn.itcast.oa.service.RoleService;
import cn.itcast.oa.service.UserService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

    // =============== ModelDriven的支持 ==================

    protected T model;

    public BaseAction() {
        try {
            // 通过反射获取model的真实类型
            ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];
            // 通过反射创建model的实例
            model = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public T getModel() {
        return model;
    }

    // =============== Service实例的声明 ==================
    @Resource
    protected RoleService roleService;
    @Resource
    protected DepartmentService departmentService;
    @Resource
    protected UserService userService;

}


抽象类是不能实例化的,所以抽象类里面的this是指实际调用中它的派生类的实例化对象      


参考文章:

http://blog.csdn.net/liang5630/article/details/40185591


本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1743536

泛型的反射

原文:http://tianxingzhe.blog.51cto.com/3390077/1743536

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!