开发者

JAXB Annotated class - setting of a variable which is not an element

I have a JAXB annotated class say

@XmlRootElement(namespace = "http://www.abc.com/customer")
Class Customer{
@XmlElement(namespace = "http://www.abc.com/customer")
  private String  Name;
  @XmlElement(namespace = "http://www.abc.com/customer")
  private String  Address;
 @XmlTransient
  private HashSet set = new HashSet();

  public String getName(){
    return Name;
  }
  public void  setName(String  name){
    this.Name = name;
    set.add("Name");
  }


  public String getAddress(){
    return Address;
  }
  public void  setAddress(String  address){
    this.Address = address;
    set.add("Address");
  }

  public void getSet(){
return set;
}

I have a XML of the form

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Customer xmlns="http://www.abc.com/customer" >
<Name>Ralph</Name>
<Address>Newton Street</Address>
</Customer>

I use JAXB unmarshalling to get the object representation of the XML input. The values for Name and Address are set correctly. However the value of set gets lost(since it is @XMLTransient it gets ignored)

Is there any way of ensuring that it is still set in the object which has been unmarshalled? Some other开发者_StackOverflow中文版 annotation which I can use?


Try putting the annotations on the methods rather than on the fields. Specifically, put @XmlElement on getName() and getAddress(), put @XmlTransient on getSet(), and remove all the annotations from the fields.

JAXB should then use the getter/setter method pairs to inject/retrieve the data, rather than the fields, and because setAddress() adds the value to the set field, that should work as you expect. Also, because getSet() is marked as transient, the contents of set should not be marshalled again.


To Avoid all this boiler plate code of XmLElement annotation all over the code. You can go ahead and use @XmlAccessType.PROPERTY at the top of the class and you can go remove all the @XmlElement Annotations. The XmlAccessType annotation takes care of telling JAXB to look at the setters and getters and not the field itself.


I suggest using some post-processor utility to fill your set. Perhaps using reflection or introspection.

Note that the postprocessor will have to inspect the JAXB annotations only, not the xml file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜