java回调函数

	protected interface Callback<E> {
		E doInCallback(Connection conn, PreparedStatement pstm, ResultSet rs)
				throws Throwable;
	}

	protected <E> E template(Callback<E> callback) throws DataAccessException {
         // 2.第一步执行
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
             // 3.进入回调方法入口
			return callback.doInCallback(conn, pstm, rs); // 6.退出执行并取得返回值
		} catch (Throwable e) {
			throw new Exception(e);
		} finally {
              // 5.返回释放资源
			ConnectionFactory.Close(pstm, rs);
		}
	}

  

//调用方法
//执行顺序:  1.执行前
Boolean result= template(new Callback<Boolean>() {
			@Override
			public Boolean doInCallback(Connection conn,
					PreparedStatement pstm, ResultSet rs) throws Throwable {
                   // 4.执行回调方法
				pstm = conn.prepareStatement(sql);
				pstm.setObject(1, id);
				int row = pstm.executeUpdate();
				return row != 0 ? true : false;
			}
		});
// 7. 从第6步取得返回值赋值给 result

  

posted on 2013-09-26 22:34  上校  阅读(302)  评论(0编辑  收藏  举报