原创

Java常用类库-AutoCloseable

继承AutoCloseable

  • 过实现AutoCloseable可以实现自动关闭
  • 自动关闭需要借助try-catch语句
    示例代码:

    interface IMessage extends AutoCloseable{
     void send(String msg);
    }
    class NetMessage implements IMessage{
     public NetMessage(){
         open();
     }
    
     public void open(){
         System.out.println("创建连接,可以开始操作。。。");
     }
     @Override
     public void send(String msg) {
         System.out.println(msg);
     }
     public void close(){
         System.out.println("任务完成,关闭连接。");
     }
    }
    public class Test2 {
     public static void main(String[] args) {
         try(NetMessage netMessage = new NetMessage();){
             netMessage.send("发送一条消息:。。。");
         }catch (Exception e){}
     }
    }
    
正文到此结束