java - Effective java Item no 74(on serialization) : Implement Serializable judiciously

标签 java effective-java

有效 java 书的第 74 项有一段(第 74 项最后的第 2 段)如下所述:

Inner classes (Item 22) should not implement Serializable. They use compiler-generated synthetic fields to store references to enclosing instances and to store values of local variables from enclosing scopes. How these fields correspond to the class definition is unspecified, as are the names of anonymous and local classes. Therefore, the default serialized form of an inner class is ill- defined.

我知道内部类使用编译器生成的合成字段来存储对封闭实例的引用,例如如果封闭类是 MyEnclosing 而内部类是 MyInner,则封闭引用是 MyEnclosing.this。但我无法获得 BOLD 部分。请帮我理解意思。谢谢!!!

最佳答案

假设你有这样一个本地类:

 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。在这种情况下,在一个编译版本中序列化并在另一个编译版本中反序列化会失败,即使使用了相同的源文件也是如此。

(此外,还有一个问题是匿名内部类没有无参数构造函数。但由于上述问题,即使是命名内部类也无法可靠地序列化)

关于java - Effective java Item no 74(on serialization) : Implement Serializable judiciously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15557783/

相关文章:

java - 使用工厂方法理解 JDBC 等服务提供者框架背后的概念

java - JSF 2.0 "Conversion Error setting value ' courseID' for 'null Converter' .!!我怎样才能避免这种错误?

java - 如何注入(inject)或替换@Resource 依赖项?

java - 如果我在 Java 中覆盖 'equals' 方法,为什么需要覆盖 hashcode?

java - 构建器模式多个可变参数

java - 如何使用单个构建器构建多个对象?

java else 没有 if 错误

java - Jersey : the resource is not available

java - XSD 架构字符串元素加密/解密

java - 终结器,关闭文件和流