Java 尝试使用资源和“AutoCloseable”接口

Dan*_*ani 2 java with-statement try-with-resources

我正在寻找 Pythonwith语句的 Java 等效项,并且我阅读了有关实现AutoCloseable接口以及对资源使用 try 的内容。

在Python中,上下文管理器(with语句)使用两种方法:__enter____exit__,但在Java中,try with resources块仅使用close,这相当于__exit__

该方法是否有等效__enter__方法,以便在进入 try with resources 块时自动执行某个方法,而不仅仅是在该块结束时?

Zir*_*con 6

等价物基本上就是您在 中调用的try任何内容来获取AutoCloseable. 这可能是一个构造函数,例如:

\n
try (MyClass obj = new MyClass()) { \xe2\x80\xa6\n
Run Code Online (Sandbox Code Playgroud)\n

具有此类构造函数的类如下所示:

\n
public class MyClass implements AutoCloseable {\n    public MyClass() {\n        // do "enter" things...\n    }\n\n    @Override\n    public void close() {\n        // close resources\n    }\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

根据您需要“输入”执行的操作,您可能更喜欢为您的类使用静态生成器,如下所示:

\n
try (MyClass obj = MyClass.getInstance(someProperties)) { \xe2\x80\xa6\n
Run Code Online (Sandbox Code Playgroud)\n

那么你的类可能看起来像这样:

\n
public class MyClass implements AutoCloseable {\n    private MyClass() {\n        // instantiate members\n    }\n\n    public static MyClass getInstance(Properties config) {\n        // you could implement a singleton pattern or something instead, for example\n        MyClass obj = new MyClass();\n        // read properties...\n        // do "enter" things...\n        return obj;\n    }\n\n    @Override\n    public void close() {\n        // close resources\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

您甚至可以在 中调用工厂或构建器模式来try生成您的AutoCloseable. 这完全取决于您的设计以及您需要实例在“输入”时执行的操作。

\n

  • “做”输入“东西......”但也要记住在那些输入的东西失败的情况下进行清理。 (3认同)