动态添加属性而不更改java对象

时间:2017-12-07 22:05:24

标签: java jaxb

我想在不更改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;
}

如果我想在XML中添加新属性4而不更改Field类(向类添加新字段并重新编译)。

有办法吗?

1 个答案:

答案 0 :(得分:1)

如果您希望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}

正如你所看到的,两个&#34;额外的&#34;属性已添加到地图中。

如果您运行相同的测试但没有任何属性,即使用xml = "<field/>";,则会得到:

field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null

attributes字段未分配,即null。它不是一张空地图。

相关问题