Is there a destructor for Java?

前端 未结 22 1582
[愿得一人]
[愿得一人] 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:28

    There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors:

    @Cleanup
    ResourceClass resource = new ResourceClass();
    

    When processing it (at compilation time), Lombok inserts appropriate try-finally block so that resource.close() is invoked, when execution leaves the scope of the variable. You can also specify explicitly another method for releasing the resource, e.g. resource.dispose():

    @Cleanup("dispose")
    ResourceClass resource = new ResourceClass();
    

提交回复
热议问题