implements Closeable or implements AutoCloseable

后端 未结 6 1220
别那么骄傲
别那么骄傲 2020-12-12 11:48

I\'m in the process of learning Java and I cannot find any good explanation on the implements Closeable and the implements AutoCloseable interfaces

6条回答
  •  执笔经年
    2020-12-12 12:08

    AutoCloseable (introduced in Java 7) makes it possible to use the try-with-resources idiom:

    public class MyResource implements AutoCloseable {
    
        public void close() throws Exception {
            System.out.println("Closing!");
        }
    
    }
    

    Now you can say:

    try (MyResource res = new MyResource()) {
        // use resource here
    }
    

    and JVM will call close() automatically for you.

    Closeable is an older interface. For some reason To preserve backward compatibility, language designers decided to create a separate one. This allows not only all Closeable classes (like streams throwing IOException) to be used in try-with-resources, but also allows throwing more general checked exceptions from close().

    When in doubt, use AutoCloseable, users of your class will be grateful.

提交回复
热议问题