McWalter.org :: 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.


// AnonAccess.java
// 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@" + 
                                       Integer.toHexString(hashCode()));
                    // store a reference to this class in a static field
                    anonClassRef=this.getClass();
                }
            };

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

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

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


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

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