What is the best way to clean up an Object in Java?

后端 未结 9 1959
悲&欢浪女
悲&欢浪女 2021-01-01 14:05

We don\'t have any destructor in Java as we have in C++.

Q1. How should we clean up any Object in java.

Q2. Is there any a

9条回答
  •  难免孤独
    2021-01-01 14:42

    Two syntax sugar options:

    1) There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors (more):

    @Cleanup
    ResourceClass resource = new ResourceClass();
    

    2) There is also try-with-resources statement. For example:

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

提交回复
热议问题