ModelDriven利用泛型实现多个Action得到不同的getModel类

[java]  view plain copy
  1. public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {  
  2. Class<T> clazz;  
  3. T t;  
  4.   
  5.     public BaseAction() {  
  6.     super();  
  7.       ParameterizedType parameterizedType =  (ParameterizedType) getClass().getGenericSuperclass();    
  8.       Type[] types = parameterizedType.getActualTypeArguments();    
  9.       clazz = (Class<T>) types[0];    
  10.       try {  
  11.          t=clazz.newInstance();  
  12.     } catch (InstantiationException e) {  
  13.         e.printStackTrace();  
  14.     } catch (IllegalAccessException e) {  
  15.         e.printStackTrace();  
  16.     }  
  17. }  
  18.   
  19.     @SuppressWarnings("unchecked")  
  20.     @Override  
  21.     public T getModel(){  
  22.         
  23.     return t;  
  24.     }  
  25.   
  26. }  

注意t是创建的类,而clazz是Class<T>这是不一样的,以后创建的action只要继承BaseAction

就可以使用封装好的t了

如下

[html]  view plain copy
  1. public class DepartmentAction extends BaseAction<Department> {  
  2. private DepartmentService departmentService;  
  3.   
  4. public DepartmentService getDepartmentService() {  
  5.     return departmentService;  
  6. }  
  7. @Resource(name="departmentServiceImpl")  
  8. public void setDepartmentService(DepartmentService departmentService) {  
  9.     this.departmentService = departmentService;  
  10. }  
  11. public String add(){  
  12.     departmentService.save(t);  
  13.     return "toList";  
  14. }  
  15. }  


注意不要把T 和Class<T>混淆,否则会出现save(Class<?>)不是save(T t)这样的错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值