Reputation: 34900
For the convenience I would like to use AutoCloseable
interface to do some stuff with the object which should be finalized before its further usage.
The only one problem is that try-with-resources
block is thing in itself, I mean that in general for obtaining reference to my AutoCloseable
instance, I have to do something like this:
MyCloseable mc;
try (MyCloseable m = mc = new MyCloseable()) {
m.doSomeStuff();
}
System.out.println(mc.getValue1());
System.out.println(mc.getValue2());
// ... and so on
Here this construction:
MyCloseable mc;
try (MyCloseable m = mc = new MyCloseable()) {
looks somewhat messy. So my question is more about design problem. I doubt for what reason java architects didn't envisage such usage of try-w-r
block as:
MyCloseable mc = new MyCloseable();
try (mc) { ... }
so may be I shoudln't use it as I described above? If it's a good practice to do that?
EDIT I was asked to explain why does my question differ from Why is declaration required in Java's try-with-resource
The explanation is very simple: I'm not asking why?, but: If it's a good practice to do that?
Upvotes: 1
Views: 791
Reputation: 3175
The intent of AutoCloseable is to automatically perform cleanups when it is no longer used.
So it would violate the principle of least astonishment to use the object after the try-with-resources block.
Upvotes: 3
Reputation: 34900
Thanks to @Tunaki, he gave me very useful link to the related question: Why is declaration required in Java's try-with-resource
I was doubted not about why this restriction exists, but I was thinking that my idea of usage is something bad from the design point of view.
But according to the fact that Java-9
will allow such usage as
MyCloseable mc;
try (mc = new MyCloseable()) { ... }
what is exactly I'm looking for, so I think, the answer to my question will be: YES, IT'S OK
Upvotes: 0