:: References to anonymous classes

Generally once can't reference an anonymous class explicitly, and instances of the class can be created only directly at the point where the anonymous class is defined.

It is possible, however, to work around this restriction - the example below shows a simple java program where the anonymous class stores its own Class in a static field, and that Class is later used to create a new instance of the anonymous class.

// Copyright (c) 2002, 2003 W.Finlay McWalter
// Licence: GPL v2

public class AnonAccess {
    static abstract class baseClass {abstract void f();}

    static Class anonClassRef;

    public static void main(String [] args){
        // initialise reference 's' to an object of an anonymous
        // concrete subclass of baseClass.
        baseClass s = new baseClass() {
                void t() {
                    System.out.println("baseclass 'constructor'");

                void f(){
                    System.out.println("  anonymous class instance@" + 
                    // store a reference to this class in a static field

        System.out.println("calling initial instance:");

        try {
            System.out.println("creating and calling subsequent instance:");
            baseClass newInstance = (baseClass)anonClassRef.newInstance();
        catch(InstantiationException e){
        catch(IllegalAccessException e){

We can do the same by getting the Class from an instance of the anonymous class:

  baseClass newInstance = (baseClass)s.getClass().newInstance();

Now, why would anyone actually want to do this? I really can't think of a good reason.