JAXB編譯器是繫結xs:boolean到Java Boolean包裝器類,而不是布林基本型別
我將專案從JAXB 1.0遷移到JAXB 2.1,並且我在資料型別對映方面遇到問題.
我正在使用Ant xjc繫結編譯器,並且我已經成功配置了全域性繫結,以便(例如)xs:date對映到java.util.Calendar.
然而,我正在生成返回Boolean的方法,我想要布林值.
這是複雜的型別:
<xs:element name="usage-auth-rate-charge"> <xs:complexType> <xs:sequence> <xs:element name="service-id" type="xs:string"/> <xs:element name="pricepoint_custom_fields_required" type="xs:boolean" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element>
生成的類看起來像這樣:
public class UsageAuthRateCharge { ........ public Boolean isPricepointCustomFieldsRequired() { return pricepointCustomFieldsRequired; }
問題是儘管拳擊將會起作用,如果提供的XML不包含pricepoint_custom_fields_required的值,則該類的布林欄位為null而不是false.所以我在做這樣的事情時得到NullPointerExceptions:
methodWhichTakesPrimitiveBooleanArg(myUsageAuthRateChargeInstance.isPricepointCustomFieldsRequired());
因為它嘗試解除傳入的布林值 – 除非它為空.
我無法更改模式,我無法調整所有客戶端程式碼進行空檢查.
我已經在我的binding.xml中設定了OptionalProperty屬性,如下所示:
<globalBindings optionalProperty="primitive">
在規範中,它說:“如果屬性的值是”原始的“,那麼它就像在JAXB 1.0”
然而這顯然沒有發生.
如何解決這個問題?
更新:
現在已經在jaxb 2.2.9中修復了:
ofollow,noindex" target="_blank">https://java.net/jira/browse/JAXB/fixforversion/16850問題
你得到Boolean而不是boolean的原因是你的元素定義中有minOccurs =“0”.將為缺少的元素儲存空值.
<xs:element name="pricepoint_custom_fields_required" type="xs:boolean" minOccurs="0"/>
解決方案應該是什麼
該解決方案應該是一個外部繫結檔案,它指示一個基本型別應該用於可選的值(參見JAXB 2.2規範的7.5.1).
<?xml version="1.0" encoding="UTF-8"?> <jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" version="2.1"> <jaxb:globalBindings optionalProperty="primitive"/> </jaxb:bindings>
外部繫結檔案使用XJC的-b選項指定.
xjc -b binding.xml my-schema.xsd
為什麼解決方案不起作用
已經開啟以下錯誤以跟蹤optionalProperty =“primitive”的問題.
>https://java.net/jira/browse/JAXB-510
>https://java.net/jira/browse/JAXB-926
解決方法
如果您不喜歡在JAXB中生成類的方式,那麼您可以自己建立一個類,並將JAXB作為模式的一部分將其作為類生成.
binding.xml
<jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1"> <jxb:bindings schemaLocation="my-schema.xsd"> <jxb:bindings node="//xs:element[@name='usage-auth-rate-charge']/complexType"> <jxb:class ref="com.example.foo.UsageAuthRateCharge"/> </jxb:bindings> </jxb:bindings> </jxb:bindings>
UsageAuthRateCharge
用你想要的方法建立這個類.
XJC電話
使用XJC呼叫上的-b標誌來指定binding.xml檔案
xjc -b binding.xml my-schema.xsd
UPDATE
What I was really hoping was that one of the readers might be a jaxbdev team member who could do the change easily in jaxb. Userarchenroot offered a possible solution in his comments on jaxb issue927 (a duplicate of 926) which leads me to think that for the rightperson, it would be a simple job to fix jaxb
我是 EclipseLink JAXB (MOXy) 領先.我已經接觸到JAXB參考實現的同事(他們也適用於Oracle).以下是我從他們那裡得到的答覆:
I’ve tested in trunk – and the problem exists.I’ll check code how easy is to fix it.
希望你能夠得到一個真正的解決這個問題.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/13035975/jaxb-compiler-is-binding-xsboolean-to-java-boolean-wrapper-class-instead-of-bo