如何使JAXB unmarshaller使用getter而不是字段

时间:2014-10-25 20:31:38

标签: jaxb marshalling unmarshalling xjc maven-jaxb2-plugin

我使用maven-jaxb2-pluginjaxbfx自动生成了一些类。后者生成带有getter和setter的JAXB类,分别在编组和解组时应该调用它们。但是,JAXB marshaller和unmarshaller方法使用字段而不是getter和setter。

以下代码显示了使用jaxbfx生成的类的示例。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyType")
public class MyType{

    @XmlAttribute(name = "id", required = true)
    protected int id;
    private final transient IntegerProperty idProxy = new SimpleIntegerProperty();

    public void setId(int value) {
        this.id = value;
        this.idProxy.set(value);
    }


    public short getId() {
        return this.idProxy.get();
    }

    public IntegerProperty idProperty() {
        return this.idProxy;
    }
}

因此,我想知道是否有可能使marshaller和unmarshaller使用getter和setter而不是字段。请注意,我无法手动更改JAXB注释,因为它们是自动生成的。

1 个答案:

答案 0 :(得分:2)

工作解决方案如下:

修改jaxbfx以清除生成的类中的所有JAXB注释:这是通过为每个要生成的类调用方法clearAllAnnotations(implClass)来实现的。

安装jaxb2-basics-annotate插件。

修改xml架构(file.xsd)以将@XmlElement批注添加到任何getter和setter方法。  例如:

   <xs:complexType name="MyType">
        <xs:attribute name="id" type="xs:int" use="required">
            <xs:annotation>
                <xs:appinfo>
                    <annox:annotate target="setter">@javax.xml.bind.annotation.XmlAttribute(required=true,name="id")
                    </annox:annotate>
                </xs:appinfo>
            </xs:annotation>
        </xs:attribute>
    </xs:complexType>
相关问题