簡體   English   中英

在JAXB中設置默認值

[英]Set default value in JAXB

我有一個如下的xml文件,當filePath2為null或為空時,我希望該值等於filePath1的值。 有沒有一種方法可以通過JAXB實現這一目標。

<file filePath1="C:/filePath">
   <subFile name="Test">
      <filePath2></filePath2>   
   </subFile>
<file/>

我不想硬編碼默認值。 如果filePath2的值為null或blank(“”),我想將filePath1屬性設置為'String filePath'的值。 有沒有辦法通過JAXB中的設置器來做到這一點?

使用純Oracle JAXB,我只能看到使用javax.xml.bind.Unmarshaller.Listener來實現的可能性。 在模型類中實現該接口,並在afterUnmarshal(..)方法中執行必要的檢查。

在那里,您可以訪問filePath1的值並將其設置(如果需要)為filePath2

感謝您的所有意見,最后我選擇了一個更簡單的解決方案。 更新在setPath中被調用的setter。 JAXB部分-

String filePath2;
@XmlElement(required = true)
public void setFilePath2(final String file) {
    this.filePath2= file;
}

使用filePath的地方-

if (filePath2 == null || filePath2.isEmpty()) {
   setFilePath2(getFilePath1());
}

如果您遇到更好但更簡單的解決方案,請告訴我。

如果可以使用注釋,那么應該可以解決問題

...
private String foo;

@XmlElement(defaultValue="bar")
public String getFoo() {
    return foo;
}
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM