synack
synack

Reputation: 1749

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.

Upvotes: 0

Views: 946

Answers (3)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

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();
}

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34367

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 );

Upvotes: 0

Robin
Robin

Reputation: 3840

I think you should try a custom serialization, like the one descriped here: https://stackoverflow.com/a/7290812/1548788

Upvotes: 0

Related Questions