思路
BaseAction
package com.itheima.web.action.base;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* 表現(xiàn)層通用實現(xiàn)
* @author Administrator
*
* @param <T>
*/
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
private T model;
//model相當(dāng)于new User
//actualTypeArguments[0];相當(dāng)于獲得User.class
public BaseAction() {
ParameterizedType genericSuperclass = (ParameterizedType)this.getClass().getGenericSuperclass();
//獲得BaseAction上聲明的泛型數(shù)組
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
Class<T> entityClass=(Class<T>) actualTypeArguments[0];
try {
//通過反射創(chuàng)建實例對象
model=entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public T getModel() {
return model;
}
}