Java尝试使用资源和“自动固有”接口
我正在寻找带有语句的Python的Java等效物,并且我阅读了有关实现AutoCoclosable
接口的信息,并将其与Resources一起使用。
在Python中,上下文管理器(语句)使用两种方法:__输入__
和__ exit __
,但是在Java中,使用Resources Block的尝试仅使用关闭
,等效于__退出__
。
__输入__
方法是否有等效词,以便在使用资源块输入尝试时自动执行某个方法,而不仅仅是块结束时?
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.
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__
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
等效的基本上是您在
尝试
中呼叫的任何内容,以获取您的AutoCoclosable
的实例。这可能是一个类似的构造函数:具有这样的构造函数的班级看起来像:
取决于您需要的“输入”要做的事情,您可能更喜欢班级的静态生产商,这看起来像这样:
那么您的班级可能会看起来像类似的内容:
您甚至可以在
尝试
中调用工厂或建筑商模式来产生您的Autococlosable
。这完全取决于您的设计以及您需要在“ Enter”上执行的实例。The equivalent is basically whatever you are calling in the
try
to get an instance of yourAutoCloseable
. This could be a constructor like:Where the class having such a constructor looks like:
Depending on what you need "enter" to do, you might instead prefer a static producer for your class, which would look like this:
Then your class might look something like this:
You could even call a factory or builder pattern in the
try
to produce yourAutoCloseable
. It all depends on your design and what you need the instance to do on "enter".