简体   繁体   中英

JAXB, annotations for setter/getter

@XmlType  
@XmlAccessorType(XmlAccessType.FIELD)  // here I need this access
public class User implements Serializable 
{  
     // ...  

     @XmlTransient
     private Set<Values> values;

     // ...

     @XmlElement
     private Set<History> getXmlHistory()
     {
         return new CustomSet<Values, History>(Values);
     }

     private void setXmlHistory(final Set<History> aHistory)
     {
         this.values = new HashSet<Values>();
     }  
}  

When I am create User object in Java code and after create XML, then all normally.
But when I try to get User-object from XML, then field values always null . So setter not working here. May be setter needs some annotation too?

XML looks like

<user>  
   ...  
      <xmlHistory>  
       // ... record 1 
      </xmlHistory>  
      <xmlHistory>  
      // ... record 2 
      </xmlHistory>  
</user>  

I do not believe that this is a JAXB problem, as the following model will work:

package forum10617267;

import java.io.Serializable;
import java.util.*;
import javax.xml.bind.annotation.*;

@XmlType
@XmlAccessorType(XmlAccessType.FIELD) // here I need this access
public class User implements Serializable {

    @XmlTransient
    private Set<History> history = new HashSet<History>();

    @XmlElement
    private Set<History> getXmlHistory() {
         return history;
    }

    private void setXmlHistory(final Set<History> aHistory) {
        this.history = aHistory;
    }

}

The problem you are seeing is a result of the logic you have in your get/set methods. Since your values field is not initialized, I am not sure how CustomSet would be able to update it.

package forum10617267;

import java.io.Serializable;
import java.util.*;
import javax.xml.bind.annotation.*;

@XmlType
@XmlAccessorType(XmlAccessType.FIELD) // here I need this access
public class User implements Serializable {

    @XmlTransient
    private Set<Values> values;

    @XmlElement
    private Set<History> getXmlHistory() {
         return new CustomSet<Values, History>(values);
    }

    private void setXmlHistory(final Set<History> aHistory) {
        this.values = new HashSet<Values>();
    }

}

I believe that @XmlAccessorType(XmlAccessType.FIELD) in combination with your @XmlTransient is the source of the problem. Have you tried without the transient annotation?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM