简体   繁体   中英

How to externalize a class that extends another

Introduction

I have the following class:

public class Foo extends ArrayList<ElementsClass> implements Externalizable {
    Field field1 = new Field();
    Field field2 = new Field();

    ...
}

I implement the methods writeExternal and readExternal like this:

public void writeExternal(ObjectOutput out) throws IOException {        
    out.writeObject(field1);
    out.writeObject(field2);
}

public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
    field1 = (Field) in.readObject();
    field2 = (Field) in.readObject();
}

Observation

One of the fields is not Serializable that is why I implement Externalizable . I want to externalize only those things that I am able to.

Problem

Although I know that the ArrayList<ElementsClass> is serializable if ElementsClass is serializable, I don't know how to externalize the class Foo itself.

Try this:

public void writeExternal(ObjectOutput out) throws IOException {        
    out.writeObject(super.toArray());
    out.writeObject(field1);
    out.writeObject(field2);
}

public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
    Object[] arr = (Object[]) in.readObject();
    for (int k=0; k<arr.length; k++) super.add(arr[k]);
    field1 = (Field) in.readObject();
    field2 = (Field) in.readObject();
}

Is it not that your class Foo is already externalized?

If you execute, statements like below, It should write the object in the file with the entries of externalized attributes.

    Foo class = new Foo();
    FileOutputStream fos = new FileOutputStream("temp");
    ObjectOutputStream oos= new ObjectOutputStream(fos);
    oos.writeObject(class );

我认为您应该尝试自定义序列化,例如此处描述的序列化: https : //stackoverflow.com/a/7290812/1548788

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM