描述:
日常工作中,经常需要使用jdbc进行数据库连接,而连接资源需要进行close()关闭操作进行释放,一般都是对connection,statement,result分别进行关闭,如下所示:
private def close(connection: Connection, statement: PreparedStatement, set: ResultSet): Unit = {
if (set != null) {
set.close()
}
if (statement != null) {
statement.close()
}
if (connection != null) {
connection.close()
}
}
做三次if判断,从代码重复的角度考虑,能否将if判断抽取为一个方法,分别调用3次该方法以实现jdbc资源的关闭。
思路:泛型
def closeOne[T](t: T):Unit = {
if (t != null){
t.close()
}
}
但是这会产生一个问题,就是若传入的类型T不支持close方法,则无法进行调用。因此此段代码在编译的时候便无法通过。
需要限制泛型的类型,即设置类型的上界。
查看Connection、PreparedStatement和ResultSet源码发现,均继承自AutoCloseable接口。
public interface Connection extends Wrapper, AutoCloseable {}
public interface Statement extends Wrapper, AutoCloseable {}
public interface ResultSet extends Wrapper, AutoCloseable {}
因此设置上界为AutoCloseable。
def closeOne[T<:AutoCloseable](t: T):Unit = {
if (t != null){
t.close()
}
}
实际效果如下:
private def close(connection: Connection, statement: PreparedStatement, set: ResultSet): Unit = {
def closeOne[T<:AutoCloseable](t: T):Unit = {
if (t != null){
t.close()
}
}
closeOne(set)
closeOne(statement)
closeOne(connection)
}
重构:利用可变参数进行map操作
以上已经实现了功能,为整体代码的整洁对其进行重构,如下:
def closed[T <: AutoCloseable](args: T*): Unit = {
args.foreach(each => {
if (each != null) {
each.close()
}
})
}