[英]Java try with resources and `AutoCloseable` interface
I am looking for a Java equivalent for python's with
statement, and I read about implementing the AutoCloseable
interface and using try with resources.我正在寻找与 python 的
with
语句等效的 Java,并且我阅读了有关实现AutoCloseable
接口和使用资源的 try 的信息。
In python, the context manager ( with
statement) uses two methods: __enter__
and __exit__
, but in Java, the try with resources block uses only close
, which is the equivalent of __exit__
.在 python 中,上下文管理器(
with
语句)使用两种方法: __enter__
和__exit__
,但在 Java 中,try with resources 块仅使用close
,相当于__exit__
。
Is there an equivalent for the __enter__
method, in order to perform a certain method automatically when entering the try with resources block, and not only when the block is over? __enter__
方法是否有等效方法,以便在进入 try with resources 块时自动执行某个方法,而不仅仅是在块结束时?
The equivalent is basically whatever you are calling in the try
to get an instance of your AutoCloseable
.等效的基本上是您在
try
获取AutoCloseable
实例时所调用的任何内容。 This could be a constructor like:这可能是一个构造函数,如:
try (MyClass obj = new MyClass()) { …
Where the class having such a constructor looks like:具有这样一个构造函数的类如下所示:
public class MyClass implements AutoCloseable {
public MyClass() {
// do "enter" things...
}
@Override
public void close() {
// close resources
}
}
Depending on what you need "enter" to do, you might instead prefer a static producer for your class, which would look like this:根据您需要“输入”执行的操作,您可能更喜欢类的静态生产者,如下所示:
try (MyClass obj = MyClass.getInstance(someProperties)) { …
Then your class might look something like this:那么你的班级可能看起来像这样:
public class MyClass implements AutoCloseable {
private MyClass() {
// instantiate members
}
public static MyClass getInstance(Properties config) {
// you could implement a singleton pattern or something instead, for example
MyClass obj = new MyClass();
// read properties...
// do "enter" things...
return obj;
}
@Override
public void close() {
// close resources
}
}
You could even call a factory or builder pattern in the try
to produce your AutoCloseable
.您甚至可以在
try
生成AutoCloseable
时调用工厂或构建器模式。 It all depends on your design and what you need the instance to do on "enter".这完全取决于您的设计以及您需要实例在“进入”时执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.