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?
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:It is possible to inject annotations at Runtime.
A guy from our company tried this on classes, see that code:
https://github.com/OlivierCroisier/AnnotationInjector/blob/master/src/main/java/net/thecodersbreakfast/annotationinjector/AnnotationInjector.java
Note that it only injects annotations on a class. He sais it's harder to do the same with methods or constructor. I'm not sure to understand all he sais in his french slides (http://www.slideshare.net/Zenika/annotations-paris-jug at the end) but it seems that what you want could be possible, but your annotations will be only on the instances in which you modify them, not all the instances (but this is perhaps what you want?)
However he didn't tell how to get the annotations map on a field or a method of a particular instance and i don't see how to get it. Note that many JDK methods returns copied values, so you cannot just modify the array of getAnnotations(), it won't have any effect... (but it seems necessary to initialize the annotations field on the class, cf his code)
Good luck, perhaps try to contact him.
Edit: you could simply make 2 different classes and choose the right one to use at runtime? this seems easier for me if you can't use MOXy. But i think you won't be able to override a method with/without xmltransient because they is no @Inherited on that JAXB annotation it seems (but i could be wrong, never tested annotation inheritence yet...
You probably can write a custom adapter (see javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter and XmlAdapter). But why do you want to do that?