About Java inner class serialization

Case 1:

public class DistributeData implements  SerializedName{
    
    

 public class CodeDetail {
    
    ...}

}

CodeDetail will not be serialized.

Case two:

public class DistributeData implements  SerializedName{
    
    

 public class CodeDetail implements  SerializedName{
    
    ...}

}

Report NotSerializableException, check for errors, although the CodeDetail class implements the Serializable interface, CodeDetail is defined in the form of an internal class in the project,

And inner classes cannot be serialized!

For inner classes, only static inner classes can be serialized. should be:

public class DistributeData implements  SerializedName{
    
    

 public static class CodeDetail implements  SerializedName{
    
    ...}

}

Therefore, try to use less internal classes and limit too much to avoid unnecessary trouble.

Case three:

public class DistributeData {
    
    

 public class CodeDetail implements  SerializedName{
    
    ...}

}

An exception is reported during operation: Objects that do not implement the serialization interface cannot be serialized.
All inner classes, Local inner classes, and anonymous inner classes can directly access the instance variables and methods of the outer encapsulation class. Whereas static nested classes cannot.
Inner classes, Local inner classes, and instances of anonymous inner classes all hold an implicit reference to an external encapsulation class instance, and Java object serialization requires that all object members in the object implement the serialization interface. Therefore, if only the inner class implements serialization, but the outer encapsulation class does not implement the serialization interface, an exception will be reported when the inner class is serialized.

Principle explanation:

Inner classes are a type of nested class, and there are four types of nested classes:

static nested class static nested class
inner class inner class (non-static)
local class local class (defined inside the method)
anonymous class anonymous class
  The behavior of static nested classes is closer to ordinary classes, and the other three are real inner classes. The difference lies in the scope.
Write picture description here

http://www.jianshu.com/p/8b8bfe1fd488

Guess you like

Origin blog.csdn.net/lrxb_123/article/details/73863807