简体   繁体   English

JAXB,setter / getter的注释

[英]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. 当我在Java代码中创建User对象并在创建XML之后,通常都是。
But when I try to get User-object from XML, then field values always null . 但是当我尝试从XML获取User-object时,字段values始终为null So setter not working here. 所以setter不在这里工作。 May be setter needs some annotation too? 可能setter也需要一些注释吗?

XML looks like XML看起来像

<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: 我不相信这是一个JAXB问题,因为以下模型将起作用:

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. 您看到的问题是您的get / set方法中的逻辑结果。 Since your values field is not initialized, I am not sure how CustomSet would be able to update it. 由于您的values字段未初始化,我不确定CustomSet如何能够更新它。

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. 我相信@XmlAccessorType(XmlAccessType.FIELD)@XmlTransient结合是问题的根源。 Have you tried without the transient annotation? 您是否尝试过没有瞬态注释?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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