Is there a destructor for Java?

前端 未结 22 1697
[愿得一人]
[愿得一人] 2020-11-22 11:47

Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?

To make my question m

22条回答
  •  被撕碎了的回忆
    2020-11-22 12:13

    Have a look at the try-with-resources statement. For example:

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
      System.out.println(br.readLine());
    } catch (Exception e) {
      ...
    } finally {
      ...
    }
    

    Here the resource that is no longer needed is freed in the BufferedReader.close() method. You can create your own class that implements AutoCloseable and use it in a similar fashion.

    This statement is more limited than finalize in terms of code structuring, but at the same time it makes the code simpler to understand and maintain. Also, there is no guarantee that a finalize method is called at all during the livetime of the application.

提交回复
热议问题