Loan Pattern / Automatic Resource Management in Java
<p>I have tried to implement automatic resource management for Java (something like C#'s <code>using</code>). Following is the code I have come up with:</p>

<pre><code>import java.lang.reflect.*;
import java.io.*;

interface ResourceUser&lt;T&gt; {
  void use(T resource);
}

class LoanPattern {
  public static &lt;T&gt; void using(T resource, ResourceUser&lt;T&gt; user) {
    Method closeMethod = null;
    try {
      closeMethod = resource.getClass().getMethod("close");
      user.use(resource);
    }
    catch(Exception x) {
      x.printStackTrace();
    }
    finally {
      try {
        closeMethod.invoke(resource);
      }
      catch(Exception x) {
        x.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    using(new PrintWriter(System.out,true), new ResourceUser&lt;PrintWriter&gt;() {
      public void use(PrintWriter writer) {
        writer.println("Hello");
      }
    });
  }
}
</code></pre>

<p>Please analyze the above code and let me know of any possible flaws and also suggest how I can improve this. Thank you.</p>

<p>(Sorry for my poor English. I am not a native English speaker.)</p>
