- public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
- Class<T> clazz;
- T t;
- public BaseAction() {
- super();
- ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
- Type[] types = parameterizedType.getActualTypeArguments();
- clazz = (Class<T>) types[0];
- try {
- t=clazz.newInstance();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- @SuppressWarnings("unchecked")
- @Override
- public T getModel(){
- return t;
- }
- }
注意t是创建的类,而clazz是Class<T>这是不一样的,以后创建的action只要继承BaseAction
就可以使用封装好的t了
如下
- public class DepartmentAction extends BaseAction<Department> {
- private DepartmentService departmentService;
- public DepartmentService getDepartmentService() {
- return departmentService;
- }
- @Resource(name="departmentServiceImpl")
- public void setDepartmentService(DepartmentService departmentService) {
- this.departmentService = departmentService;
- }
- public String add(){
- departmentService.save(t);
- return "toList";
- }
- }
注意不要把T 和Class<T>混淆,否则会出现save(Class<?>)不是save(T t)这样的错误