我正在尝试序列化一个简单的层次结构:
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;
}
}
当我跑
时SubClass sub = new SubClass();
Serializer serializer = new Persister();
StringBuilderWriter writer = new StringBuilderWriter(1000);
serializer.write(sub, writer);
我明白了:
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
我找不到任何方法让它发挥作用。
答案 0 :(得分:0)
什么是Serializer?如果要序列化对象,则应实现Serializable接口。这是我的代码:
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();
}
答案 1 :(得分:0)
您需要传递类似的值。
class SubClass extends RootClass {
@Element(name="b")
int b;
public SubClass(@Element(name="a")int a) {
super(a);
this.b=0;
}
}
或试试这个
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);
}
}
上面的工作方式与java对象中的readResolve()和writeReplace()相同