Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4093279

IllegalAccessException due to package access no-arg constructor of nonserializ

XMLWordPrintable

    • 1.1.6
    • sparc
    • solaris_2.6
    • Verified

        The javadoc for Serializable.java, ObjectOutputStream and ObjectInputStream,
        and the Serialization specification itself talk about how nonserializable superclasses/supertypes are dealt with. Specifically, they all say that the nonserializable superclass must have "an accessible no-arg constructor",
        with accessible being either public, protected, or package-private wrt the serializable subclass.
        This does not match the behaviour of the code, which seems to require that
        the nonserializable superclass have a "public" no-arg constructor. If the no-arg constructor is otherwise, you get an IllegalAccessException.
        This seems to make sense from the implementation point of view, since
        ObjectInputStream is the class that's invoking the no-arg constructor and hence requires it to be public.

        Here's a test program:

        TestVer.java:

        import java.io.*;

        class TestSer {
            public static void main(String[] args) {
                try {
                    FileOutputStream f = new FileOutputStream("Class1.ser");
                    ObjectOutputStream out = new ObjectOutputStream(f);

                    Class1 c1 = new Class1();
                    c1.field2 = "hello";
                    out.writeObject(c1);
                    out.flush();
                    out.close();

                    FileInputStream f2 = new FileInputStream("Class1.ser");
                    ObjectInputStream in = new ObjectInputStream(f2);

                    Class1 cc1 = (Class1) in.readObject();
                    in.close();
                    System.out.println(cc1.field2);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        Class1.java
        import java.io.Serializable;

        public class Class1 extends Class2 implements Serializable {
            public int field1;
            public String field2;
        }

        Class2.java:
        public class Class2 {
            int f1;
            int f2;

            protected Class2() {
                f1 = f2 = 100;
            }
        }

         

              jfialli Joe Fialli
              rleesunw Rosanna Lee (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

                Created:
                Updated:
                Resolved:
                Imported:
                Indexed: