Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

java - How to use JAXB annotations at runtime

I have the following bean class

@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;
}
}

and the corresponding marshalling code

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) {
        }
    }
}

I want to make the attributes configurable at runtime ,i want to specify @xmltransient on "num" at runtime not compile time.how can i do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

The MOXy JAXB implementation offers the ability to manipulate the mapping metadata at runtime via its MetadataSource extension. For a detailed example see:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...