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 块时自动执行某个方法,而不仅仅是在该块结束时?
等价物基本上就是您在 中调用的try任何内容来获取AutoCloseable. 这可能是一个构造函数,例如:
try (MyClass obj = new MyClass()) { \xe2\x80\xa6\nRun Code Online (Sandbox Code Playgroud)\n具有此类构造函数的类如下所示:
\npublic 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\nRun Code Online (Sandbox Code Playgroud)\n根据您需要“输入”执行的操作,您可能更喜欢为您的类使用静态生成器,如下所示:
\ntry (MyClass obj = MyClass.getInstance(someProperties)) { \xe2\x80\xa6\nRun Code Online (Sandbox Code Playgroud)\n那么你的类可能看起来像这样:
\npublic 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}\nRun Code Online (Sandbox Code Playgroud)\n您甚至可以在 中调用工厂或构建器模式来try生成您的AutoCloseable. 这完全取决于您的设计以及您需要实例在“输入”时执行的操作。
| 归档时间: |
|
| 查看次数: |
908 次 |
| 最近记录: |