views:

223

answers:

2

When I pass an anonymous inner class into a function, I can refer to variables in the current scope from within a method of that class, like so:

class Caller {
    private Object callerPrivate;

    // ...

    public void someMethod() {
        final String callerLocal = "Eyes only";

        ISomeInterface anon = new ISomeInterface() {
                                     public void doSomethingInterfacy {
                                         System.out.println(callerPrivate.toString());
                                         System.out.println(callerLocal);
                                     }
                                  };
        // this is some other object that puts ISomeInterfaces in a queue
        // and makes them doSomethingInterfacy later
        myCallManager.enqueue(anon);
    }
}

Now, after someMethod above has been run, the Caller and the queue with the little anons can go separate ways, and, as far as I understand it, the JVM keeps all the references straight so that this always works.

But what if, for example, the queue gets serialized, the program shut down and restarted, and after that the queue gets deserialized and the items in it shall be run, with the Caller instance long gone and forgotten?

And are there other ways for the surrounding object and the anonymous inner class to get separated in a way that calls inside the anon class won't work anymore?

+5  A: 

Don't serialise local classes, because (a) the docs say so and (b) the serial representation is not stable (they don't have a stable name for a start).

If you don't want your instance to keep fields for outer this and used final locals, use a (static) nested class or an outer class. For (Java) serialisation, you can use writeReplace to serialise a serial proxy object.

Tom Hawtin - tackline
+2  A: 

Don't forget that your anonymous inner class contains an implicit this reference. i.e. a reference to the surrounding class.

So if you serialise your inner class, there will be a reference to your outer class. You can see this clearly if you serialise using XStream and view the XML output.

Brian Agnew