RuntimeAnnoatationReader to read custom annotation

2019-09-02 02:32发布

问题:

How RuntimeAnnotationReader can be used for JAXB annotations to read Custom Annotations and control class fields at runtime.While searching on google i found this link http://glassfish.10926.n7.nabble.com/injecting-JAXB-annotations-at-runtime-td59852.html but i couldn't gather much information about RuntimeAnnotationReader. I have the following reqirement: Suppose I have a class name Person.java

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement(name="Person")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Student.class})
public class Person <T>{

private T payload;
@XmlElement(name = "Person-Name")
private String name;

public void setPayload(T payload){
    this.payload = payload;
}

public T getPayload(){
    return payload;
}

public void setName(String name){
    this.name = name;
}

public String getName(){
    return name;
}
}

and student.java:

  package RuntimeAnnotation;

  import javax.xml.bind.annotation.XmlAccessType;
  import javax.xml.bind.annotation.XmlAccessorType;
  import javax.xml.bind.annotation.XmlElement;
  import javax.xml.bind.annotation.XmlRootElement;

  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public class Student {

@XmlElement
private String name;

@XmlElement
private String id;

public void setName(String name) {
    this.name = name;
}

public String getName(){
    return name;
}

public void setId(String id){
    this.id = id;
}

public String getId(){
    return id;
}
  }

While initializing person class object, i am setting payload field as student object. Now while marshalling XML output shows payload as tagname, but I want student should be appear at tagname.

Marshal output:

 <Person>
     <payload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="student">
      <name>ABC</name>
      <id>239423</id>
  </payload>
<Person-Name>XYZ</Person-Name>
</Person>

Expected output:

<Person>
<T>
    <name>ABC</name>
    <id>239423</id>
<T>
<Person-Name>XYZ</Person-Name>
</Person>

P.S.: should be the parametrized class name. In the above case T should be Student.

回答1:

To answer your question, see Annox for an example of a custom Annotation Reader implementation:

https://svn.java.net/svn/annox~svn/trunk/core/src/main/java/org/jvnet/annox/xml/bind/AnnoxAnnotationReader.java

Disclaimer: I'm the author of Annox and many other JAXB utilities.

But apart from that I don't think you really need this runtime tricks to achieve your goal. Read more on @XmlElementRef and JAXBElement. You can get your XML by having a payload like:

@XmlElementRef
JAXBElement<T> payload;