在父类中反射获取泛型类型

  使用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;

}
原文地址:https://www.cnblogs.com/Yiran583/p/4224103.html