分享一個本身寫的JFinal的BaseController (2)java
今天偶然翻博客,發現本身走了彎路啊。this
把model的class保存成變量不用每次去取。.net
原本就已經獲得class了,我還去forName,由於當時從第一個版本修改到第二個版本,因此沒細看。第一個版本也是一樣的問題。code
修改後的BaseController代碼以下blog
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import com.jfinal.core.Controller; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Page; import com.jfinal.plugin.activerecord.Record; /** * 繼承此類的子類具有基本的CRUD * * @author hexin * * @param <M> Model */ public class BaseController<M extends Model<M>> extends Controller { public BaseController() { // 把class的變量保存起來,不用每次去取 this.setModelClass(getClazz()); } /** * 獲取M的class * * @return M */ @SuppressWarnings("unchecked") public Class<M> getClazz() { Type t = getClass().getGenericSuperclass(); Type[] params = ((ParameterizedType) t).getActualTypeArguments(); return (Class<M>) params[0]; } protected Class<M> modelClass; public Class<M> getModelClass() { return modelClass; } public void setModelClass(Class<M> modelClass) { this.modelClass = modelClass; } /** * 通用分頁查找 */ public void getByPage() { Page<Record> list = Db .paginate(getParaToInt("pageNumber"), getParaToInt("pageSize"), "select *", "from " + getModelClass().getSimpleName() + " order by id desc"); renderJson(list); } /** * 通用查找所有 */ public void getAll() { renderJson(Db.find("select * from " + getModelClass().getSimpleName() + " order by id asc;")); } /** * 通用根據id查找 */ public void getById() { renderJson(Db.findById(getModelClass().getSimpleName(), getParaToInt("id"))); } /** * 通用新增 * * @throws Exception */ public void save() throws Exception { renderText((getModel(getModelClass())).save() + ""); } /** * 通用修改 * * @throws Exception */ public void update() throws Exception { renderText(getModel(getModelClass()).update() + ""); } /** * 通用刪除 * * @throws Exception */ public void delete() throws Exception { renderText(getModel(getModelClass()).delete() + ""); } }