javaexternalizable

Externalization with inner classes


I was going through article on Externalization on this site and I found the following para in the limitations of Externalization section.

As you know a default public no-arg constructor will be called when serializing the objects that implements Externalizable interface. Hence, Externalizable interface can't be implemented by Inner Classes in Java as all the constructors of an inner class in Java will always accept the instance of the enclosing class as a prepended parameter and therefore you can't have a no-arg constructor for an inner class. Inner classes can achieve object serialization by only implementing Serializable interface.

I tested this and turns out this is not valid. Inner classes can have no argument constructor and also they can implement Externalizable interface. Even tried it with local classes. Works fine.

public class ExternalizeDemo {

    class InnerClass implements Externalizable{

        public InnerClass() {
            //default no-arg inner class constructor
        }

        @Override
        public void writeExternal(ObjectOutput out) throws IOException {
            //logic to save object state
        }

        @Override
        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            //logic to retrieve object state
        }
    }

    public void localClassTest(){
        class LocalClass implements Externalizable{

            public LocalClass(){
                //default no-arg local class constructor
            }

            @Override
            public void writeExternal(ObjectOutput out) throws IOException {
                //logic to save object state
            }

            @Override
            public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
                //logic to retrieve object state
            }
        }
    }

}

So either I am missing some point or the article paragraph is no longer valid (I am using Java 7). So which one is it. Any suggestion is appreciated.


Solution

  • The paragraph means you cannot create instance of inner class (non static nested class) without an instance of outer class.

    So on deserializing to create instance of inner class the code will need somehow to use an instance of the outer class.

    You have to call

    ExternalizeDemo mainClassInstance=some initializing;
    
    mainClassInstance.new InnerClass();
    

    Deserializing won't have the mainClassInstance to create the InnerClass instance.