为什么这是不可能的?它看起来很简单,但它的行为并不像预期的那样。
摘要:A 类使用聚合的 DataA bean,而 B 类(A 类的子类)使用聚合的 DataB bean(而 DataB 扩展 DataA)。
我编写了这些测试类来可视化和解释我的问题:
A类:
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class A {
private DataA source = new DataA();
@XmlElement(name="source")
public DataA getSource() {
return source;
}
public void setSource(DataA source) {
this.source = source;
}
}
及其 DataA 类(我使用了 FIELD 注释,以便对所有字段进行编组):
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.FIELD)
public class DataA {
public String string1 = "1";
public String string2 = "2";
}
现在是 B 类(A 类的子类):我的目标是重用 A 的功能,并通过使用 DataB bean 重用来自 DataA bean 的属性:
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class B extends A {
private DataB source = new DataB();
public DataB getSource() {
return this.source;
}
public void setSource(DataB source) {
this.source = source;
}
}
其对应的 DataB bean 如下所示:
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.FIELD)
public class DataB extends DataA {
public String string3 = "3";
}
现在,当我编组 A 类的一个实例时,它会给出以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<source>
<string1>1</string1>
<string2>2</string2>
</source>
</root>
当我编组 B 类的一个实例时,我得到了完全相同的结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<source>
<string1>1</string1>
<string2>2</string2>
</source>
</root>
但我预计 string3 也会被编组,但它只是编写 bean DataA 的属性!为什么?在考虑 OOP 时,这并不是很直观。
当我也在 B 类上设置 @XmlElement 注释时......像这样:
@XmlElement
public DataB getSource() {
return this.source;
}
...然后该属性被编组两次,因为它曾经被父类和子类注释过。这也是我不想要的:
现在的输出是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<source xsi:type="dataB" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string1>1</string1>
<string2>2</string2>
<string3>3</string3>
</source>
<source>
<string1>1</string1>
<string2>2</string2>
<string3>3</string3>
</source>
</root>
因此,我对 JAXB 的期望是以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<source>
<string1>1</string1>
<string2>2</string2>
<string3>3</string3>
</source>
</root>
任何提示如何调整 JAXB 以产生预期的结果?感谢您的任何反馈。