25
April

Anonymous inner classes in Java

Posted in: Java technologies (translated), Java technologies, J2SE |

The Russian version of this article can be found here.
There are a lot of articles through Internet which have mistakes regarding anonymous inner classes in Java. Anonymous inner class:

  • has no name;
  • can’t be declared as static;
  • can be instantiated only once.

Let me show you the truth.
Consider the following code:

public class Anonymous {
    public static void main(String[] args) {
        Runnable anonym = new Runnable() {
            public void run() {
            }
        };
    }
}

In order to get the name of inner class write down the following:

anonym.getClass().toString().

You’ll get something like that: Anonymous$1.
Anonymous class can be either static or non-static. It depends on the block in which the class have been declared. In the previous example the anonymous class was static. In this case we can create the second instance of this class in such a way:

Runnable anonym2 = (Runnable) anonym
    .getClass().newInstance().

There is no need in type cast in JDK 1.5.
If the anonymous class was declared in non-static block, we have to provide a reference to the outer class to the proper constructor (in reflection veritas!). In the other case we’ll get the InstantiationException.
Here we have an example (determining of proper constructor and exception handling are not shown below):

public class Anonymous {
  public void nonStaticMethod() {
    Runnable anonym = new Runnable() {
      public void run() {
      }
    };
    Constructor[] constructors = anonym.getClass()
        .getDeclaredConstructors();
    Object[] params = new Object[1];
    params[0] = this;

    Runnable anonym2 = (Runnable) constructors[0]
        .newInstance(params);
  }

  public static void main(String[] args) {
    Anonymous example = new Anonymous();
    example.nonStaticMethod();
  }
}

In this example we have to use getDeclaredConstructors instead of getConstructors. Method getConstructors will return only public constructors, while needed constructor is protected one.
I really do appreciate your comments on this article. Have a nice day.

No Comments yet »

RSS feed for comments on this post. TrackBack URI



Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>