我想在字段中添加另一个新属性而不更改 java 对象。
<field attribute1 = "1" attribute2 = "2" attribute3 = "3"> value</filed>
@XmlRootElement(name = "field ")
public class Field
{
@XmlAttribute(name="attribute1")
private String attribute1;
@XmlAttribute(name="attribute2")
private String attribute2;
@XmlAttribute(name="attribute3")
private String attribute3;
}
如果我想在不更改 Field 类的情况下向 XML 添加新属性 4(向类添加新字段并重新编译)。
有办法做到这一点吗?
最佳答案
如果您希望 Java 类能够存储任何属性,您需要 Map
要存储属性名称/值对,您需要使用 @XmlAnyAttribute
注释该字段.
这里是示例代码:
@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
@XmlAttribute(name="attribute1")
String attribute1;
@XmlAttribute(name="attribute2")
String attribute2;
@XmlAttribute(name="attribute3")
String attribute3;
@XmlAnyAttribute
Map<String, String> attributes;
}
测试
String xml = "<field attribute1=\"A\"" +
" attribute2=\"B\"" +
" attribute3=\"C\"" +
" attribute4=\"D\"" +
" foo=\"Bar\" />";
JAXBContext jaxbContext = JAXBContext.newInstance(Field.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Field field = (Field) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("field.attribute1 = " + field.attribute1);
System.out.println("field.attribute2 = " + field.attribute2);
System.out.println("field.attribute3 = " + field.attribute3);
System.out.println("field.attributes = " + field.attributes);
输出
field.attribute1 = A
field.attribute2 = B
field.attribute3 = C
field.attributes = {attribute4=D, foo=Bar}
如您所见,两个“额外”属性已添加到 map 中。
如果您运行相同的测试但没有任何属性,即使用 xml = "<field/>";
,你得到:
field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null
attributes
字段未分配,即 null
。这不是一张空 map 。
关于java - 动态添加属性而不改变java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704608/