有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有内部类的java外部化

我正在浏览this网站上关于外部化的文章,在“外部化的限制”一节中找到了以下段落

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.

我测试了一下,结果证明这是无效的。内部类可以没有参数构造函数,也可以实现Externalizable接口。甚至在当地的课堂上也尝试过。很好

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
            }
        }
    }

}

因此,要么我遗漏了某一点,要么文章段落不再有效(我使用的是Java 7)。那么是哪一个呢。任何建议都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    它在运行时失败。。。下面的向导类是SerialiserTest的内部类,实现了Externalizable

    Wizard w = new SerialiserTest().new Wizard();
    outputStream = new ByteArrayOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(w);
    byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
    inputStream = new ObjectInputStream(byteArrayInputStream);
    Wizard wiz = (Wizard) inputStream.readObject();
    
    Exception in thread "main" java.io.InvalidClassException: jtk.file.ser.SerialiserTest$Wizard; no valid constructor
    at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:150)