0

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.

synack
  • 1,699
  • 3
  • 24
  • 50

3 Answers3

1

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();
}
Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
0

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 );
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • Your code would throw a `NotSerializable` Exception because my `Foo` class contains a Field that is not serializable. That's why I implement Externalizable. – synack Oct 10 '12 at 16:56
  • This is why you are using `Externalizable` in place of `Serializable`. In `writeExternal`, directly write the fields, which are `serializable`. For `non-searializable` fields, get the internal attributes manually and then write them. You need to the `reverse` of the same in `readExternal` method. – Yogendra Singh Oct 10 '12 at 17:07
  • I don't need to Externalize the fields that are not Serializable. I just skip them. The problem is that I need to externalize the class itself and I don't know how to do it. – synack Oct 15 '12 at 07:23
  • @Kits89 You have already accepted the answer which is very similar to what I mentioned here. Not sure, what else are you expecting? – Yogendra Singh Oct 15 '12 at 12:50
0

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

Community
  • 1
  • 1
Robin
  • 3,512
  • 10
  • 39
  • 73