Accessing member variable within an anonymous inner class

I'm getting a compiler error with the following snippet which resides in a constructor (error below):
        final String fullNamesArr[] = new String[ lafsArr.length ];
        String lafNamesArr[] = new String[ lafsArr.length ];
        JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
        for ( int i = 0 ; i < lafsArr.length ; i++ )
            StringTokenizer tokenizer;
            fullNamesArr[ i ] = lafsArr[ i ].getClassName();
            tokenizer = new StringTokenizer( fullNamesArr[ i ] );
            while ( tokenizer.hasMoreTokens() )
                lafNamesArr[ i ] = tokenizer.nextToken( "." );
            namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
            lafMenu.add( namesMenuItemArr[ i ] );
            namesMenuItemArr[ i ].addActionListener(new ActionListener()
                    public final void actionPerformed(final ActionEvent e)
                        String actionCommand = e.getActionCommand();
                        int iCount = 0;
                        for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                            if ( fullNamesArr[ index ].contains( actionCommand ))
                                iCount = index;
                                break;
                        System.out.println( "Setting LAF to '" +
                                            fullNamesArr[ iCount ] + "'" );
                        try
                            UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                        catch ( UnsupportedLookAndFeelException ulafe )
                            System.out.println( fullNamesArr[ iCount ] +
                                                " : Not a valid LAF class." );
                        catch ( ClassNotFoundException cnfe )
                            System.out.println( fullNamesArr[ iCount ] +
                                                " : Class not found." );
                        catch ( InstantiationException ie )
                            System.out.println( fullNamesArr[ iCount ] +
                                                " : Can't instantiate class." );
                        catch ( IllegalAccessException iae )
                            System.out.println( fullNamesArr[ iCount ] +
                                                " : Illegal access." );
DBBuilder.java:1280: cannot resolve symbol
symbol : method contains (java.lang.String)
location: class java.lang.String
if ( fullNamesArr[ index ].contains( actionCommand ))
^
1 error
BUILD FAILED
My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
TIA,
Jeff

My question: Why can I access fullNamesArr in other
spots in the anon-inner class,but not with the
String.contains() method? BTW, the carrot is under
the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

Similar Messages

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • Catch-22: need to assign a local variable within an anonymous class

    static boolean showMessage(Window parent, String button0, String button1)
        throws HeadlessException {
              final Window w = new Window(parent);
              Panel p = new Panel(new GridBagLayout());
              final Button b[] = new Button[]{new Button(button0), (button1 != null) ? new Button(button1) : (Button)null};
              boolean rval[]; //tristate: null, true, false
              w.setSize(100, 50);
              w.setVisible(true);
              //add b[0
              gbc.fill = GridBagConstraints.HORIZONTAL;
              gbc.gridx = 0;
              gbc.gridy = 3;
              p.add(b[0], gbc);
              //add b[1]
              if (button1 != null) {
                   gbc.fill = GridBagConstraints.HORIZONTAL;
                   gbc.gridx = 1;
                   gbc.gridy = 3;
                   p.add(b[1], gbc);
              w.add(p);
              w.pack();
            w.setVisible(true);
            //actionListener for button 0
              b[0].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (e.getSource() == b[0]) {
                                  w.setVisible(false);
                                  rval = new boolean[1];
                                  rval[0] = true;
              //actionListener for button 1
              if (button1 != null) {
                   b[1].addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) {
                                  if (e.getSource() == b[1]) {
                                       w.setVisible(false);
                                       rval = new boolean[1];
                                       rval[0] = false;
            while (true) {
                 try {
                      if (rval[0] == true || rval[0] == false) //should trigger NullPointerException
                           return rval[0];
                 } catch (NullPointerException e) { }
         }catch-22 is at
    rval = new boolean[1];
    rval = false;javac whines: "local variable rval is accessed from within inner class; needs to be declared final"
    How do I assign to rval if it's declared final?
    Or at the very least, how do I get rid of this error (by all means, hack fixes are okay; this is not C/C++, I don't have to use sanity checks)?
    I'm trying to make a messagebox in java without using JOptionPane and I'm trying to encapsulate it in one method.
    And I'm far too lazy to make a JNI wrapper for GTK.

    dcminter wrote:
    How do I assign to rval if it's declared final?You don't and you can't. You're not allowed to assign to the local variable of the outer class for extremely good reasons, so forget about trying.
    Or at the very least, how do I get rid of this errorIf you don't want the side effect, then just use an inner class variable or a local variable.
    If you want the side effect then use a named class and provide it with a getter and setter.
    Finally, in this specific case because you're using an array object reference, you could probably just initialise the array object in the outer class. I.e.
    // Outer class
    final boolean[] rval = new boolean[1];
    // Anonymous Inner class
    rval[0] = true; // No need to intialize the array.
    I declared it as an array so that it would be a tristate boolean (null, true, false) such that accessing it before initialization from the actionPerformed would trigger a NullPointerException.
    Flowchart:
    is button pressed? <-> no
    |
    V
    Yes->set and return
    Is there a way to accomplish this without creating a tribool class?

  • Semi-Anonymous Inner Class?

    From API description of invokeLater method of SwingUtilities class:
    /* begin quote
    In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
    Runnable doHelloWorld = new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    SwingUtilities.invokeLater(doHelloWorld);
    System.out.println("This might well be displayed before the other message.");
    */ end quote
    The interface class is named (doHelloWorld) so it's not really anonymous.
    But the class is not declared; there's no class keyword.
    Is there a formal name for this construction?
    It seems like a hybrid of named and anonymous implementation.
    I guess the ability to mix class declaration, instantiation, method declaration, etc in one statement is powerful but just hard for beginner to understand when to use.
    Sigh, three ways to do same thing. This 'hybrid' form is actually harder to understand than other ways.
    private class myRunnable implements Runnable {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    myRunnable doHelloWorld = new myRunnable();
    OR
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    Thanks,
    Stanley.

    The interface class is named (doHelloWorld) so it's
    not really anonymous. No. There's a variable that points to an instance of that class, and the variable is named doHelloWorld. The class is anonymous.
    Is there a formal name for this construction?Anonymous inner class.

  • Cant complie "anonymous inner class" on JDK1.4

    public Enumeration enumerator()
    return new Enumeration()
    int currentItem = items.size() - 1;
    public boolean hasMoreElements() {
    return (currentItem >= 0);
    error: cant resolve symbol
    help me! thanx u very much

    Since Enumeration is an interface, the anonymous inner class needs to implement both functions.
    public Enumeration enumerator()
      return new Enumeration()
         int currentItem = items.size() - 1;
         public boolean hasMoreElements()
            return (currentItem >= 0);
         public Object nextElement()
            return items.elementAt(currentItem--);
    }I assume that items is a member field of the class containing this method. Since I don't know what it is , the elementAt is only a guess.

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

  • Adapters vs anonymous inner class (please help)

    I am trying to clean up my code by using anonymous inner classes to handle some action events. My code looks like this but I get an error
    Button.addActionListener(new MyClass() {
    public void actionPerformed(ActionEvent e) {
    my_Button_actionPerformed(e);
    it says that it cant find MyClass, but I thought I dont need to define it becaue I am defining it here, isnt that the point of a anonymous inner class

    yourBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
    });(BTW: use code tags in posting!)

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Anonymous Inner Class question

    How can I get "foof" to be echoed to the screen?
    class MyClass {
       void go() {
          Bar b = new Bar();
          b.doStuff(new Foo() {
             public void foof() {
                System.out.println("foof");
    interface Foo {
       void foof();
    class Bar {
       void doStuff(Foo f) {}
    public class TestWonder {
       public static void main (String... args) {
       new MyClass().go();
       //Why doesn't this print out "foof" to the screen? Nothing is echoed to the screen.
    }

    Sorry to be so thick, but I thought that the code did that already. Apparently it doesn't. In other words, how would the code invoke the override foof()? I should be clearer:
    I know if I change Bar's doStuff() to
    void doStuff(Foo f) {
    System.out.println("bar's dostuff");
    }then when go() is executed bar's dostuff will print out. But, what about the override in the anonymous inner class?
    Edited by: RonNYC2 on Feb 5, 2010 1:03 PM
    Edited by: RonNYC2 on Feb 5, 2010 1:05 PM

  • Anonymous inner class

    Hello
    In the following piece of code:
    import static tools.Print.*;
    interface ForInner {
         void who();
         String toString();
    class ForInnerWithParameters {
         int i;
         String s;
         ForInnerWithParameters(int i) {
              this.i = i;
    class NackedClass {
         public ForInner inner() {
              return new ForInner() {
                   private int i;
                        print("Inside inner class!");
                        i = 10;
                   public int getI() {
                        return i;
                   public void who() {
                        print("It's me, inner!");
                   public String toString() {
                        return "Anonymous class";
         public ForInnerWithParameters innerWith(int i, final String s) {
              return new ForInnerWithParameters(i) {
                   {     print("i = "+i);
                        print(s);
                        super.s = s;
                   public String getS() {
                        return s;
         public static void main(String[] args) {
              NackedClass nc = new NackedClass();
              ForInner fi = nc.inner();
              fi.who();
              ForInnerWithParameters fiwp = nc.innerWith(91, "Hello");
              print(fiwp.i);
              print(fiwp.s);
    i would like to assign to the variable s (inside ForInnerWithParameters class) the value "Hello" passed as a parameter in the main ( ForInnerWithParameters fiwp = nc.innerWith(91, "Hello"); )
    The method innerWith(int i, final String s) is getting the values 91 and "Hello". Both, the parameter in the method and the parameter in the class are named s. How can I assign the value s ("Hello") to the parameter s inside the class? this.s = s or super.s = s doesn't work. The only solution I found is to change either the name of the parameter s inside the method or the name of the parameter s inside the class.
    I hope the question is clear enough!
    Thanks a lot!

    I would have expected this.s to work, providing you used it every time (including getS()).
    But, to be honest, why bother? It's just pointlessly confusing to use s as your method parameter.

  • Accessing member variable

    Hello techies,
    Iam trying to access the member variables of an object which is added to arrayList.
    I had 2 arrayLists.
    Now i am converting it into Object[] using toArray()
    Now iam comparing these two arraylists.
    Now iam trying to access the memeber vairables of each object which is added to arraylist .
    But iam unable to access the member variable of each object.
    Object a[] = a1.toArray();
              Object b[] = a2.toArray();
              for (int i = 0; i < a.length; i++) {
                   System.out.println("inside for loop");
                   for (int j = 0; j < b.length; j++) {
    // a.
                        int o = compareObjects.compare(a[i], b[j]);
                        System.out.println("returned value is" + o);
    Here is my code::
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    class exampleObject implements Comparator {
         String s = null;
         int i;
         int o;
         public exampleObject() {
         public exampleObject(int p, int q) {
              i = p;
              o = q;
         public int compare(Object o1, Object o2) {
              exampleObject k = (exampleObject) o1;
              exampleObject kk = (exampleObject) o2;
              // System.out.println("k.i"+k.i);
              // System.out.println("kk.i"+kk.i);
              if (k.i == kk.i) {
                   System.out.println("inside if condition" + k.i);
                   System.out.println("same i values");
                   if (k.o == kk.o) {
                        System.out.println("kk.o");
                   } else {
                        System.out.println("same p values");
                        return kk.o;
              return k.i;
    class ArrayListObjectCompare {
         // public static BufferedReader readFile;
         public static exampleObject ex;
         public static void main(String args[]) {
              ArrayList a1 = new ArrayList();
              ArrayList a2 = new ArrayList();
              ex = new exampleObject(2, 3);
              exampleObject ex1 = new exampleObject(3, 4);
              exampleObject ex2 = new exampleObject(4, 5);
              exampleObject ex3 = new exampleObject(5, 6);
              exampleObject ex4 = new exampleObject(6, 7);
              a1.add(ex);
              a1.add(ex2);
              a1.add(ex4);
              a2.add(ex1);
              a2.add(ex3);
              exampleObject compareObjects = new exampleObject();
              Object a[] = a1.toArray();
              Object b[] = a2.toArray();
              for (int i = 0; i < a.length; i++) {
                   System.out.println("inside for loop");
                   for (int j = 0; j < b.length; j++) {
    // a[i].k(-----here iam getting error);
                        int o = compareObjects.compare(a[i], b[j]);
                        System.out.println("returned value is" + o);
    can any tell me how to access the member variable of each object which is added to arrayList.
    I will be very thankful if any body replies or modifies my code.
    thanks(inadvance),
    ramu

    I'm not sure if they work 100% correctly yet after the forum "upgrade" last week, but please use code tags (see button above posting box) when posting code.
    You need to cast your Object back to exampleObject:
    exampleObject myObj = (exampleObject)a[0];
    System.out.println(myObj.i);Or, try using the other "toArray" overload:
    exampleObject a[] = a1.toArray(new exampleObject[a1.size()]);Then your "a" array elements are already of class exampleObject, and you don't need to cast each element individually.

  • How to pass a variable value to an inner class?

    Hi there,
    Please have a look of the code below. It's a bit long, but my concern is I did have to declare the int "i" variable as static because it is used by an inner class (if "i" is not declare as static, the code cannot be compiled).
    Is there a more "clean" way to do the way work without declaring the "i" int as static? (because the scope of this variable is not the whole program).
    Thanks for your help.
    Denis
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Runnable(){
                        public void run(){
                             myApp.jpb.setValue(Tools.i);//--- static variable i
                   for (int j=0; j<200; j++)
                        System.out.println(Tools.i+" - "+j);
    class myListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
              Thread t = new Thread() {
                   public void run(){
                        Tools.longTask();
              t.start();
    public class myApp {
         static JProgressBar jpb;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JPanel panel = new JPanel(new FlowLayout());
              jpb = new JProgressBar();
              jpb.setValue(0);
              jpb.setStringPainted(true);
              JButton button = new JButton("go");
              button.addActionListener(new myListener());
              panel.add(jpb);
              panel.add(button);
              frame.getContentPane().add( panel, BorderLayout.CENTER);
              frame.setVisible(true);
              frame.pack();
    }

    Without compiling it, writing it in notepad, it would be something like this. You should also wonder if this longTask has to be static by the way. But I think this demonstrates the inner class stuff. You can also look in the tutorial on this site: http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Innerclass(i));
                   for (int j=0; j<200; j++) {
                        System.out.println(Tools.i+" - "+j);
         Class Innerclass implements Runnable(){
              int i;
              public Innerclass(int i) {
                   this.i = i;
              public void run(){
                   myApp.jpb.setValue(Tools.i);//--- static variable i
    }

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • Pass an array of argument defined anonymous inner class

    Can someone plz tell me what is wrong with this code?How can I correct it?
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[5]{
                   public void disp(){
                        System.out.println("Array of inner classes disp");
    }     

    This is what I wanted to do:
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
              ni[1].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[]{
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside first implementor of NotImplemented interface");
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside second implementor of NotImplemented interface");
    Thanks for all your help...

Maybe you are looking for