简体   繁体   English

JAXB - 从XSD生成类 - 将枚举转换为字符串

[英]JAXB - generating classes from XSD - converting enums to strings

Using JAXB, we generate our Java beans directly. 使用JAXB,我们直接生成Java bean。 In the XSD, we have an enumerated type: 在XSD中,我们有一个枚举类型:

  <xs:simpleType name="promptBeforeCloseType">
    <xs:restriction base="xs:string">
     <xs:enumeration value="default"/>
     <xs:enumeration value="always"/>
     <xs:enumeration value="never"/>
    </xs:restriction>
  </xs:simpleType>

JAXB generates an enumerated type for the field using this type. JAXB使用此类型为字段生成枚举类型。 We would like to have it converted to a String in the generated Java class, because those classes are mapped to ActionScript classes, and there is no enumerated type in ActionScript. 我们希望将它转换为生成的Java类中的String,因为这些类映射到ActionScript类,并且ActionScript中没有枚举类型。

Is there a way to do it, implementing some kind of converter ? 有没有办法实现它,实现某种转换器? May be with XmlJavaTypeAdapter ? 可能与XmlJavaTypeAdapter一起

You can force XJC to not generate enums. 您可以强制XJC不生成枚举。 See the "Global Binding Declarations" section of this document : 请参阅本文档的“全局绑定声明”部分:

If typesafeEnumBase is set to xsd:string, it would be a global way to specify that all simple type definitions deriving directly or indirectly from xsd:string and having enumeration facets should be bound by default to a typesafe enum. 如果typesafeEnumBase设置为xsd:string,那么它将是一种全局方式,用于指定直接或间接从xsd:string派生并具有枚举构面的所有简单类型定义应默认绑定到类型安全枚举。 If typesafeEnumBase is set to an empty string, "", no simple type definitions would ever be bound to a typesafe enum class by default. 如果将typesafeEnumBase设置为空字符串“”,则默认情况下,任何简单的类型定义都不会绑定到类型安全的枚举类。

jaxb:globalBindings typesafeEnumBase =“xs:boolean”将起作用 - 将其留空,因为建议对绑定模式无效。

Check out the [Overriding the Datatype][1] section of the JAXB tutorial. 查看JAXB教程的[覆盖数据类型] [1]部分。 You can do this with a customised bindings file set up similar to the example at the bottom of the page. 您可以使用类似于页面底部示例的自定义绑定文件设置来完成此操作。

I think you'd have to write your own conversion method (and thus class) unfortunately since there doesn't seem to be one built-in (likely due to the fact that the JAXB-generated enums have no common superclass). 我认为你不得不编写自己的转换方法(因此类),因为似乎没有一个内置(可能是因为JAXB生成的枚举没有共同的超类)。 But all you'd need to do is call the value() method on your enum object, which will return the String that mapped to it. 但是你需要做的只是在你的enum对象上调用value()方法,它将返回映射到它的String。

[1]: https://jaxb.dev.java.net/tutorial/section_5_6_1-Overriding-the-Datatype.html#Overriding the Datatype [1]: https//jaxb.dev.java.net/tutorial/section_5_6_1-Overriding-the-Datatype.html#Overriding the Datatype

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

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