IDisposable metaphor in Java?

后端 未结 6 1231
滥情空心
滥情空心 2021-02-19 13:44

As a java developer getting into .NET I\'d like to understand the IDisposable interface. Could somebody please try to explain this and how it differs from what happens in Java?

6条回答
  •  忘了有多久
    2021-02-19 14:21

    With java 1.7 there is the new introduced try-with-resource statement.

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
    

    The objects used here must implement AutoCloseable interface. It is not exactly the same as IDisposable, but the close() is called automatically in the finally. This gives the oportunity to implement similar behavior.

    The code above is the same as

    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
    

    Read more about this in java tutorial. The samplecode is coming from there.

提交回复
热议问题