title: Call method on object in try-with-resources block
body: <p>The <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="nofollow">Java tutorial</a> state that you can do the following with <code>try-with-resources</code>:</p>
  
  <pre><code>try (Statement stmt = con.createStatement()) {
      ResultSet rs = stmt.executeQuery(query);
      ...
  } catch (SQLException e) {
      ...
  }
  </code></pre>
  
  <p>In this tutorial the <code>ResultSet</code> is never closed, thus I want to include the <code>ResultSet</code> , as it also implements the <code>AutoCloseable</code> interface, like so:</p>
  
  <pre><code>try (Statement stmt = con.createStatement(); 
       ResultSet rs = stmt.executeQuery(query)) {
      ...
  } catch (SQLException e) {
      ...
  }
  </code></pre>
  
  <p>This works fine, but when it comes to <code>PreparedStatements</code> I want to be able to set some values on the <em>before</em> executing the query:</p>
  
  <pre><code>String name = "Ian";
  try (PreparedStatement pstmt = getPreparedStatement(con, stmt); 
       pstmt.setString(1, name);
       ResultSet rs = pstmt.executeQuery(query)) {
      ...
  } catch (SQLException e) {
      ...
  }
  </code></pre>
  
  <p>This causes a range of compilation errors, because (I am assuming) only variable assignment is allowed.</p>
  
  <p>Is there anyway to do this neatly in the same <code>try-with-resources</code> block?</p>
  
  <p>I have already thought of:</p>
  
  <ol>
  <li>Nested try-with-resources (which is what I am trying to avoid). I realise there is nothing 'wrong' with doing so, I merely want to do this for the sake of readability.</li>
  </ol>
  
  <p>Consider the following to cases:</p>
  
  <pre><code>try (MyObject1 o1 = new MyObject1()) {
      o1.setSomeValue();
      try (MyObject2 o2 = new MyObject2(o1)) {
          o2.setSomeValue();
          try (MyObject3 o3 = new MyObeject3(o2) {
              o3.setSomeValue();
              // do work here
          }
      }
  } catch (Exception e) {
      ...
  }
  </code></pre>
  
  <p>vs</p>
  
  <pre><code>try (MyObject1 o1 = new MyObject1();
       o1.setSomeValue();
       MyObject3 o2 = new MyObeject2(o1);
       o2.setSomeValue();
       MyObject3 o3 = new MyObeject3(o2);
       o3.setSomeValue()) {
  
      // do work here
  } catch (Exception e) {
      ...
  }
  </code></pre>
  
  <ol start="2">
  <li>Having <code>setString()</code> method return the object and include it in assignment</li>
  <li>Creating some sort of helper method that creates the connection and sets parameters accordingly.</li>
  </ol>
  
  <p>Something like:</p>
  
  <pre><code>public PreparedStatement createPreparedStatement(Connection con, String stmt, Object ... params) {
  
  }
  </code></pre>