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

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

在父类中反射获取泛型类型使用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;}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航