using java anonymous functions to return values
<p>Transitioning from C# to Java and attempting to clean up a bunch of Connection leaks in some code.</p>

<p>To prevent leaks in I would have done something like</p>

<pre><code>public class DB{
    public interface StatementUser{
         public void useit(Statement cmd);
    }

    public static void UseCommand(StatementUser usingfunc){
        try(Connection cnn = new Connection(...)){
            cnn.open();
            try(Statement stmt = new Statement(cnn)){
                usingfunc(stmt);
            }
        }
    }

    static void main(string[] args){
        int affected = 0;
        DB.useStatement((stmt) -&gt; {
            // THIS STATEMENT IS DISALLOWED
            affected = ... select/update... whatever
        });
        System.out.println("Records: " + affected);
    }
}
</code></pre>

<p>I like this delegate because it handles the cleanup but still leaves most of the interaction with the data to the developer's creativity.</p>

<p>I get that the assignment to <code>affected</code> is considered accessing a variable outside of its scope, and not allowed. So now I'm kind of at a loss as to how to perform a similar operation in Java (I want to maintain the generic usage of the connection/statement object)</p>

<p>Everything I've come up with just makes it uglier, so I suspect I'm simply heading down a completely dead-end path.</p>

<p>What is a Java way of doing something like this? (I get that this may look drastically different than I'm expecting)</p>