Java 中可以使用 RAII 吗?
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
这种设计模式在Java中是否可行?如果是这样,怎么办?如果没有,为什么不呢?
谢谢!
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
Is this design pattern possible in Java? If so, how? If not, why not?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您链接到的同一维基百科页面有一个关于 Java 的部分,引用:
我认为 Java 7 有一个提案,它将创建 Closeable 类,以及
try
块的一些语法糖,以使其更加简洁(但您仍然需要编写try
try代码>块)。The same Wikipedia page that you linked to has a section on Java, quote:
I think there is a proposal for Java 7, which would create Closeable classes, and some syntactic sugar for the
try
blocks to make this more concise (but you still have to write thattry
block).如果在同一范围内获取多个资源,您将需要本文中精心设计的稳健方法:
http://www.javalobby.org/java/forums/t19048.html
总结如下。
请阅读原始链接以了解为什么需要这样,以及为什么其他任何内容(例如其他答案中提出的链接)都不够。
With multiple resource acquisitions within the same scope, you would need the approach, which is carefully designed to be robust, within the article:
http://www.javalobby.org/java/forums/t19048.html
which is summarized below.
Do read the original link to understand why it needs to be this way and why anything else, like the one proposed in the other answers, would not suffice.