Effective java-element number 74 (serialization): it is reasonable to implement Serializable

Paragraph 74 of the effective java book contains a paragraph (second paragraph from the last paragraph 74), which is mentioned below:

Inner classes (clause 22) must not implement Serializable. They use compiler-generated synthetic fields to store references to instances and to store the values ​​of local variables from attachment sights. How these fields correspond to the definition of the unpecified class, as well as the names of anonymous and local classes. Therefore, the standard serialized form of the inner class is bad, defined.

I know that the inner class uses a compiler generated by a synthetic field to store references to surrounding instances, for example. if the inclusion class is MyEnclosing and the inner class is MyInner, then the attached reference is MyEnclosing.this. But I can’t get the BOLD part . Please help me understand the meaning. Thank!!!

+5
source share
3 answers

Suppose you have a local class:

 class OuterClass {
    Runnable run;

    void method() {
       final int a = 8;
       this.run = new Runnable() {
          public void run() {
             System.out.println(a);
          }
       };
    }
 }

, this, . OuterClass$1 val$a. , , . OuterClass$method$1. , .

( , , no-args. - )

+6

:

public class Main {
    public static void main(String[] args) {
        final int x = Integer.valueOf(args[0]);
        new Object() {
            void print() {
                System.out.println(x);
            }
        }.print();
    }
}

Main$1. , , x val$x:

private final int val$x;

, .

+1

- , :

class Outer implements Serializable {
    private String someString;

    class Inner implements Serializable {
        private int someInt;
    }

}

Inner, , ( Outer.this) . :

class Outer implements Serializable {
    private String someString;

    Serializable method(final int i) {
        class Inner implements Serializable {
            Inner() {
                System.out.println(i);
            }
        }
        return new Inner();
    }
}

, method(), i, .

0

All Articles