Is there a way for anonymous inner classes in Java to “lose” their scope?

When I pass an anonymous inner class to a function, I can refer to variables in the current scope inside the method of this class, for example:

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 executing some method above, Caller and the queue with small announcements can go in different ways, and, as I understand it, the JVM saves all the links right so that it always works.

But what if, for example, the queue is serialized, the program shuts down and restarts, and after that the queue is deserialized and the elements in it are started, and the Caller instance is long gone and forgotten?

And are there other ways for the surrounding object and the anonymous inner class to be separated in such a way that calls inside the anon class will no longer work?

+3
2

, () , (b) ( ).

, , () . (Java) writeReplace -.

+6

, . .

, , . , XStream XML.

+2

Source: https://habr.com/ru/post/1705172/


All Articles