2008/06/17

Calling method of anonymous class

I though that it is an axiom of Java language specification - one cannot call new method defined in anonymous class outside the scope of this class. I was wrong. :)

public class AnonymousClassMethod {

  public static void main(String[] args) {
    (new Object() {
      void foo() {
        System.out.println("foo");
      }
    }).foo();
  }
}

This code just prints foo

But what is the purpose of such construct. Here is simple example which came to my mind:

public class Caller {

  public static void main(String[] args) {
    System.out.println((new Subject()).getCallerClass());
  }

}
public class Subject {

  public Class getCallerClass() {
    return (new SecurityManager() {
      Class getCallerClass() {
        return getClassContext()[1];
      }
    }).getCallerClass();
  }

}

Crazybob has another example.

No comments:

Post a Comment