How to use JAXB annotations at runtime

前端 未结 3 754
感情败类
感情败类 2020-12-18 16:12

I have the following bean class

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

private String name;
priv         


        
相关标签:
3条回答
  • 2020-12-18 17:00

    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:

    • http://blog.bdoughan.com/2011/06/moxy-extensible-models-refresh-example.html
    0 讨论(0)
  • 2020-12-18 17:03

    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...

    0 讨论(0)
  • 2020-12-18 17:05

    You probably can write a custom adapter (see javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter and XmlAdapter). But why do you want to do that?

    0 讨论(0)
提交回复
热议问题