java lambda使用
jdk8+以上引入了箭头函数,即J8的lambda表达式。
Lambda表达式的本质只是一个"语法糖",由编译器推断并帮你转换包装为常规的代码,因此你可以使用更少的代码来实现同样的功能。
在阅读jdbctemplate源码时候,看到一段这样的代码
return updateCount(execute(psc, ps -> {
//箭头函数,这里执行了回调功能
try {
if (pss != null) {
pss.setValues(ps);
}
int rows = ps.executeUpdate();
if (logger.isTraceEnabled()) {
logger.trace("SQL update affected " + rows + " rows");
}
return rows;
}
finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
}
}
}));
继续看execute
@Override
@Nullable
public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
throws DataAccessException {
Assert.notNull(psc, "PreparedStatementCreator must not be null");
Assert.notNull(action, "Callback object must not be null");
if (logger.isDebugEnabled()) {
String sql = getSql(psc);
logger.debug("Executing prepared SQL statement" + (sql != null ? " [" + sql + "]" : ""));
}
Connection con = DataSourceUtils.getConnection(obtainDataSource());
PreparedStatement ps = null;
try {
ps = psc.createPreparedStatement(con);
applyStatementSettings(ps);
T result = action.doInPreparedStatement(ps);
handleWarnings(ps);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
if (psc instanceof ParameterDisposer) {
((ParameterDisposer) psc).cleanupParameters();
}
String sql = getSql(psc);
psc = null;
JdbcUtils.closeStatement(ps);
ps = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("PreparedStatementCallback", sql, ex);
}
finally {
if (psc instanceof ParameterDisposer) {
((ParameterDisposer) psc).cleanupParameters();
}
JdbcUtils.closeStatement(ps);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
上述代码是通过lambda进行回调操作,PreparedStatementCallback是接口,同时只有单实现
满足条件:
1、基于接口的回调
2、接口只能是单实现
下边是我们基于上述回调机制进行的代码实现:
接口:TestLambda
public interface TestLambda {
public void prints(String str);
}
基于接口进行回调操作,lambda和非lambda实现
public class TestMain {
public static void main(String[] args) {
test(new TestLambda() {
@Override
public void prints(String str) {
System.out.println("hello:"+str);
}
});
test(str->{
System.out.println("ni:"+str);
});
}
public static void test(TestLambda tl){
tl.prints("11111");
}
}

浙公网安备 33010602011771号