Why would you ever implement finalize()?

前端 未结 21 2651
耶瑟儿~
耶瑟儿~ 2020-11-22 16:50

I\'ve been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize()

21条回答
  •  长发绾君心
    2020-11-22 17:28

    The resources (File, Socket, Stream etc.) need to be closed once we are done with them. They generally have close() method which we generally call in finally section of try-catch statements. Sometimes finalize() can also be used by few developers but IMO that is not a suitable way as there is no guarantee that finalize will be called always.

    In Java 7 we have got try-with-resources statement which can be used like:

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
      // Processing and other logic here.
    } catch (Exception e) {
      // log exception
    } finally {
      // Just in case we need to do some stuff here.
    }
    

    In the above example try-with-resource will automatically close the resource BufferedReader by invoking close() method. If we want we can also implement Closeable in our own classes and use it in similar way. IMO it seems more neat and simple to understand.

提交回复
热议问题