为什么XmlEncoder不将类的成员插入到xml文件中?

时间:2012-02-01 09:09:32

标签: java xml-serialization

我正在尝试将一些数据放入XML文件中。这是代码:

@Test
public void TestProximities() {

    // Create a proximity 
    ISpaceComponent solarSystem = Init.createSolarSystemProximities();
    solarSystem.runTtest();

    Path filePath = Paths.get("c:\\temp\\junk.bin");

    File xmlFile = new File("c:\\temp\\");
    boolean success = xmlFile.mkdirs();
    if (!success && ! xmlFile.exists() ) {
        // Directory creation failed
        System.out.println("Failed to create a file: " + filePath);
    }

    try {
        XMLEncoder fileXml = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("c:\\temp\\junk.xml") ) );
        fileXml.writeObject(solarSystem);
        fileXml.flush();
        fileXml.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getMessage());

    }

}

Init.createSolarSystemProximities():

public static ISpaceComposite createSolarSystemProximities() {

    // Proximities
    ISpaceComposite solarSystem = new SpaceComposite("The Solar System");
    solarSystem.addComponent(new Star("Sol"));      

    ISpaceComposite MercuryProximity = new SpaceComposite("Mercury proximity");
    MercuryProximity.addComponent(new Planet("Mercury"));
    solarSystem.addComponent(MercuryProximity);

    ISpaceComposite VenusProximity = new SpaceComposite("Venus proximity");
    VenusProximity.addComponent(new Planet("Venus"));
    solarSystem.addComponent(VenusProximity);

    ISpaceComposite EarthProximity = new SpaceComposite("Earth proximity");
    EarthProximity.addComponent(new Planet("The Earth"));
    EarthProximity.addComponent(new Moon("The Moon"));
    solarSystem.addComponent(EarthProximity);

    ISpaceComposite MarsProximity = new SpaceComposite("Mars proximity");
    MarsProximity.addComponent(new Planet("Mars"));
    MarsProximity.addComponent(new Moon("Phobos"));
    MarsProximity.addComponent(new Moon("Deimos"));
    solarSystem.addComponent(MarsProximity);

    return solarSystem;

} 

太空复合类看起来像这样:

public class SpaceComposite extends SpaceComponent implements ISpaceComposite {
    public static final long serialVersionUID = Data.serialVersionUID;
    private ArrayList<ISpaceComponent> _components;
private int _currentMoonIndex;

}

'SpaceComposite'也有默认的无参数构造函数。但是唯一插入到文件中的是它的名字,来自'SpaceComponent'类

public abstract class SpaceComponent implements ISpaceComponent, Serializable{
    private String _title;
    public static final long serialVersionUID = Data.serialVersionUID;

    // Default constructor
    public SpaceComponent(){
        _title = "";
    }
 }

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

XmlEncoder使用JavaBean约定捕获属性。它的工作原理是克隆对象图并记录创建克隆所需的步骤。您希望在没有任何自定义的情况下使用XmlEncoder的类需要遵循JavaBeans约定(getXYZ/setXYZ用于属性,或isAbc/setAbc用于布尔属性等。)我的猜测是唯一可用的属性,如你的班级是Name,因此它是唯一被序列化的班级。

链接中的文章还解释了如何通过提供自己的持久性委托来自定义流程,但我会先尝试添加getter / setter,看看是否足以使其工作。