Java回调函数实例
生活随笔
收集整理的這篇文章主要介紹了
Java回调函数实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以JDBC的回調函數操作為例:
1、定義一個回調函數接口:用于收集查詢結果并轉換成實體
import java.sql.ResultSet; import java.sql.SQLException; import java.util.List;public interface ResultSetCall<T> {public List<T> getList(ResultSet resultSet) throws SQLException;}2、定義一個參數回調接口和默認實現類,用于填充參數 import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;public interface PrepareStatementCall {public PreparedStatement getPrepareStatement(Connection con, String sql, Object[] params) throws SQLException; }import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;public class DefaultPrepareStatementCall implements PrepareStatementCall{@Overridepublic PreparedStatement getPrepareStatement(Connection con, String sql, Object[] params) throws SQLException {CallableStatement pre = con.prepareCall(sql);for(int i=0;i<params.length;i++){pre.setObject(i+1, params[i]);}return pre;}}
3、調用Dao: public abstract class BaseDao<T> {protected DataSource dataSource;private PrepareStatementCall call = new DefaultPrepareStatementCall();public List<T> queryList(String sql, Object[] params, PrepareStatementCall call, ResultSetCall<T> resultSetCall){Connection con = null;PreparedStatement pre = null;ResultSet set = null;List<T> rs = null;try {con = dataSource.getConnection();pre = call.getPrepareStatement(con, sql, params);set = pre.executeQuery();rs = resultSetCall.getList(set);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{this.colseResultSet(set);this.colsePreparedStatement(pre);this.colseConnection(con);}return rs;}4、調用示例: List<CompleteTask> rs = super.queryList(COMPLETE_NEW_SQL, new Object[]{waybillStatus, eachFetchDataNum}, new ResultSetCall<CompleteTask>(){@Overridepublic List<CompleteTask> getList(ResultSet set) throws SQLException {List<CompleteTask> rs = new ArrayList<CompleteTask>();while(set.next()){CompleteTask task = new CompleteTask();task.setTaskId(<span style="font-family: Arial, Helvetica, sans-serif;">set.getInt("taskId")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span>task.setTaskType(<span style="font-family: Arial, Helvetica, sans-serif;">set.getInt("taskType")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span> <span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>return rs; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} </span>
總結
以上是生活随笔為你收集整理的Java回调函数实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux lsof/netstat查看
- 下一篇: Javascript弹出div层