如何在运行时使用JAXB批注


问题内容

我有以下豆类

@XmlRootElement(name = "book")
//Optional
@XmlType(propOrder = {"name" })
public class Book {

private String name;
private int num;

@XmlTransient
public int getNum() {
    return num;
}

public void setNum(int num) {
    this.num = num;
}

// name for your XML-Output:
@XmlElement(name = "bookName")
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

以及相应的编组代码

private static void marshalXML(Book bookstore) {

    Writer w = null;
    try {
        // create JAXB context and instantiate marshaller
        JAXBContext context = getContext();
        if (context != null) {
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(bookstore, System.out);
            w = new FileWriter(BOOKSTORE_XML);
            m.marshal(bookstore, w);
        }
    } catch (Exception e) {
        System.out.println("error in marshalling");
    } finally {
        try {
            w.close();
        } catch (Exception e) {
        }
    }
}

我想使属性在运行时可配置,我想在运行时在“ num”上指定@xmltransient而不进行编译。我该怎么办?


问题答案:

注意: 我是 EclipseLink
JAXB(MOXy)的
负责人,并且是 JAXB
2(JSR-222)
专家组的成员。

MOXy JAXB实现提供了通过其MetadataSource扩展在运行时操纵映射元数据的功能。有关详细示例,请参见: