Jox doesn't handle relations to other objects. It's very
easy to get into an never-ending-loop.
A small solution is to implement a registry of objects
(ie ThreadLocal) to detect cyclical object references and
avoid infinite loops.
Works fine with java.beans package.
This following code will crash the JVM with a
StackOverflowError :
public class Test {
public static void main(String[] args) {
Test test = new Test();
Test1 test1 = new Test1();
test1.setField1("field1");
Test2 test2 = new Test2();
test2.setField2("field2");
test2.setRelation(test2);
OutputStream stream = new
ByteArrayOutputStream();
// Jox
JOXBeanOutputStream joxOut = new
JOXBeanOutputStream(stream);
try {
joxOut.writeObject("Test1", test1);
joxOut.close();
System.out.println(stream.toString());
// Crash here
joxOut.writeObject("Test2", test2);
joxOut.close();
System.out.println(stream.toString());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
// Beans
XMLEncoder encoder = new XMLEncoder(stream);
try {
encoder.writeObject(test1);
encoder.close();
System.out.println(stream.toString());
encoder.writeObject(test2);
encoder.close();
System.out.println(stream.toString());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class Test1 {
private String field1;
/**
* Constructor
*/
public Test1(){
// Nop
}
/**
* Get the field1.
*
* @return the field1.
*/
public String getField1() {
return this.field1;
}
/**
* Set the field1
*
* @param field1 field1 to set.
*/
public void setField1(String field1) {
this.field1 = field1;
}
}
public class Test2 {
private String field2;
private Test2 relation;
/**
* Constructor
*/
public Test2(){
// Nop
}
/**
* Get the field2.
*
* @return the field2.
*/
public String getField2() {
return this.field2;
}
/**
* Set the field2
*
* @param field2 field2 to set.
*/
public void setField2(String field2) {
this.field2 = field2;
}
/**
* Get the relation.
*
* @return the relation.
*/
public Test2 getRelation() {
return this.relation;
}
/**
* Set the relation
*
* @param relation relation to set.
*/
public void setRelation(Test2 relation) {
this.relation = relation;
}
}