What is the best way to emulate try-with-resources in Java 6?

后端 未结 3 1492
感情败类
感情败类 2021-01-17 18:18

It turns out that almost nobody closes resources in Java correctly. Programmers either do not use try-finally block at all, or just put resource.close()

3条回答
  •  逝去的感伤
    2021-01-17 19:19

    Though anonymous class is quite verbose, it's still acceptable in java land

        new TryWithResource(){
            protected InputStream init() throws Exception {
                return new FileInputStream("abc.txt");
            }
            protected void use(InputStream input) throws Exception{
                input.read();
            }
        };
    
    ----
    
    abstract class TryWithResource
    {
        abstract protected R init() throws Exception;
        abstract protected void use(R resource) throws Exception;
    
        // caution: invoking virtual methods in constructor!
        TryWithResource() throws Exception
        {
            // ... code before
            R r = init();
            use(r);
            // ... code after
        }
    }
    

提交回复
热议问题