-------- Original message --------
From: Damjan Jovanovic 
Date:11/03/2013 03:30 (GMT-05:00) 
To: Commons Developers List 
Subject: Backporting try-with-resources to Java < 7 (was: Re: [imaging] Closing 
stream) 

On Fri, Oct 25, 2013 at 1:52 PM, Matt Benson <gudnabr...@gmail.com> wrote:

> On Oct 25, 2013 6:30 AM, "Damjan Jovanovic" <damjan....@gmail.com> wrote:
> >
> > On Fri, Oct 25, 2013 at 12:36 PM, Jörg Schaible
> > <joerg.schai...@scalaris.com> wrote:
> > > Hi Damjan,
> > >
> > > Damjan Jovanovic wrote:
> > >
> > > [snip]
> > >
> > > Thanks for explanation.
> > >
> > >> We would be able to adapt that for Java < 1.7 by swallowing the close
> > >> exception instead of calling addSuppressed() on the primary exception,
> > >> but the show stopper is catching and rethrowing the primary exception
> > >> (Throwable), which javac < 1.7 refuses to compile because it doesn't
> > >> do "Rethrowing Exceptions with More Inclusive Type Checking"
> > >> (
>
> http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
> ).
> > >>
> > >> But this would work and always sets succeeded correctly without
> > >> catch/re-throw:
> > >>
> > >> final InputStream is = factoryMethodThatCanThrow();
> > >> boolean succeeded = false;
> > >> try {
> > >>     try {
> > >>         is.methodThatCanThrow();
> > >>     } finally {
> > >>     }
> > >>     succeeded = true;
> > >> } finally {
> > >>     closeSafely(!succeeded, is);
> > >> }
> > >
> > > I guess the nested try was unintentionally ;-)
> > >
> > > Cheers,
> > > Jörg
> >
> > Well that actually won't work, because the "succeeded = true;" will be
> > skipped if there is a "return;" in the inner try.
> >
> > Other than a custom Java compiler, I guess there's no clean way of
> > doing this in Java < 1.7. There's really only option 2 - with being
> > careful to always set succeeded correctly on all paths out of the try
> > block. Almost like releasing memory in C.
> >
>
> I haven't deeply followed this conversation, but would this be a candidate
> for a [weaver] module?
>
> Matt
>
>

[weaver] I am less sure about, but by playing with Objectweb's ASM I did
manage to compile code with try-with-resources on Java 7, change the class
file version, do some bytecode manipulation to delete calls to
Throwable.addSuppressed(), and get it to work on Java < 7.

Made it into a Maven plugin and it works well :). Also verified other Java
7 language features (binary literals, underscores in numeric literals,
strings in switch, diamonds, exception multi-catch and re-throw) work on
Java < 7 because they're just syntactic sugar.

It's very small and simple - 143 lines in 1 file. Is it worth adding as a
new commons project? Or do we not host (projects that contain) Maven
plugins?

We already host a build plug in of some kind IIRC with 
http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22commons-build-plugin%22

Gary
Damjan

Reply via email to