Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 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 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...