title: Why am I having this InstantiationException in Java when accessing final local variables?
body: <p>I was playing with some code to make a &quot;closure like&quot;  construct ( not working btw )</p>
  <p>Everything looked fine but when I tried to access a final local variable in the code, the exception <code>InstantiationException</code> is thrown.</p>
  <p>If I remove the access to the local variable either by removing it altogether or by making it class attribute instead, no exception happens.</p>
  <p>The doc says: <a href="http://java.sun.com/javase/6/docs/api/java/lang/InstantiationException.html" rel="noreferrer">InstantiationException</a></p>
  <blockquote>
  <p><em>Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:</em></p>
  <p><em>- the class object represents an abstract class, an interface, an array class, a primitive type, or void</em></p>
  <p><em>- the class has no nullary constructor</em></p>
  </blockquote>
  <p>What other reason could have caused this problem?</p>
  <p>Here's the code. comment/uncomment the class attribute / local variable  to see the effect (lines:5 and 10 ).</p>
  <pre><code>import javax.swing.*;
  import java.awt.event.*;
  import java.awt.*;
  class InstantiationExceptionDemo {
       //static JTextField field = new JTextField();// works if uncommented
  
      public static void main( String [] args ) {
          JFrame frame = new JFrame();
          JButton button = new JButton(&quot;Click&quot;);
          final JTextField field = new JTextField();// fails if uncommented
  
          button.addActionListener( new _(){{
              System.out.println(&quot;click &quot; + field.getText());
          }});
      
          frame.add( field );
          frame.add( button, BorderLayout.SOUTH );
          frame.pack();frame.setVisible( true );
      
      }
  }
  class _ implements ActionListener {
      public void actionPerformed( ActionEvent e ){
          try {
              this.getClass().newInstance();
          } catch( InstantiationException ie ){
              throw new RuntimeException( ie );
          } catch( IllegalAccessException ie ){
              throw new RuntimeException( ie );
          }
      }
  }
  </code></pre>
  <p>Is this a bug in Java?</p>
  <p><strong>edit</strong></p>
  <p>Oh, I forgot, the stacktrace ( when thrown ) is:</p>
  <pre><code>Caused by: java.lang.InstantiationException: InstantiationExceptionDemo$1
  at java.lang.Class.newInstance0(Class.java:340)
  at java.lang.Class.newInstance(Class.java:308)
  at _.actionPerformed(InstantiationExceptionDemo.java:25)
  </code></pre>