AutoCloseable接口的使用

jdk1.7引入了资源自动关闭的接口AutoCloseable。一些资源也实现了该接口,如preparedStatement、Connection、InputStream、outputStream等等资源接口。在使用的时候只需要把资源在try块中用小括号括起来就可以了。

String sql = "select 1 from dual";
		try 
			(
				PreparedStatement pstmt = toConn.prepareStatement(sql);
				PreparedStatement pstmt1 = fromConn.prepareStatement(sql);
				ResultSet rs = pstmt.executeQuery();
				ResultSet rs1 = pstmt1.executeQuery()
			)
			{
				if(rs.next() || rs1.next()){
				}
			}
		catch (SQLException e) {
			log.error("test conn fail:", e);
			e.printStackTrace();
			throw new IllegalStateException("mysql链接发生异常!");
		}
小括号里的资源最后一句不能加“;”。想要关闭的资源放里面,不需要在finally里再写rs.close,pstmt.close了。
 
可以做个小实验,验证下AutoCloseable接口的作用
 
<p>public class TestAutoColseable {</p><p> public static void main(String[] args)  {</p><p>  try
   (MyResource mr = new MyResource())
  {
   mr.doSomething();
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   
  }
  
 }
}</p>
 
<p>public class MyResource implements AutoCloseable{</p><p> @Override
 public void close() throws Exception {
  System.out.println("资源被关闭了!");
 }
 
 public void doSomething(){
  System.out.println("干活了!");
 }
}
</p>
 
运行main方法就可以看到效果了。


 

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值