simple-framework - how to pass member to super class

387 views Asked by At

I'm trying to serialize a simple hierarchy:

public class RootClass {
    @Element
    private final int a;

    public RootClass( int a) {
        this.a = a;
    }
}

class SubClass extends RootClass {

    @Element(name="b")
    int b;

    public SubClass() {
        super(0);
        this.b=0;
    }
}

when I run

SubClass sub = new SubClass();
Serializer serializer = new Persister();
StringBuilderWriter writer = new StringBuilderWriter(1000);
serializer.write(sub, writer);

I get:

ConstructorException: Default constructor can not accept read only 
@org.simpleframework.xml.Element(name=, data=false, type=void, required=true) 
on field 'a' private final int 
com.informatica.b2b.structurediscovery.serialization.tests.RootClass.a in class 
com.informatica.b2b.structurediscovery.serialization.tests.SubClass

I couldn't find any way to make it work.

2

There are 2 answers

0
yushulx On

What is Serializer? if you want to serialize your object, you should implement the interface Serializable. Here is my code:

public class RootClass implements Serializable{
    private final int a;

    public RootClass(int a) {
        this.a = a;
    }

    public void print(){
        System.out.println(a);
    };
}
public class SubClass extends RootClass {
    int b;

    public SubClass() {
        super(0);
        this.b = 0;
    }

    public void print() {
        super.print();
    }
}

        SubClass sub = new SubClass();
        sub.print();
        try {
            File file = new File("SubClass");
            if (!file.exists())
                file.createNewFile();
            FileOutputStream fileOut = new FileOutputStream(file);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(sub);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
0
ng. On

You need to pass in the value for a like so.

class SubClass extends RootClass {

    @Element(name="b")
    int b;

    public SubClass(@Element(name="a")int a) {
        super(a);
        this.b=0;
    }
}

Or try this

class SubClassSubstitute  {

    @Element
    int a;

    @Element
    int b

    public SubClassSubstitute(@Element(name="a")int a, @Element(name="b")int b){
       this.a = a;
       this.b = b;
    }

    @Resolve
    public SubClass resolve() {
       return new Subclass(a)
    }
}


class SubClass extends RootClass {

    @Element(name="b")
    int b;

    public SubClass(@Element(name="a")int a) {
        super(a);
        this.b=0;
    }

    public SubClassDelegate replace() {
       return new SubClassSubstitute(a, b);
    }
}

The above works the same as readResolve() and writeReplace() in java object