我有一个问题,JAXB正在为
XML模式生成绑定类(为了精度,我无法修改).
我想将xsd:date类型映射到Joda-Time LocalDate对象,并且读取 here,here和 here,我创建了以下DateAdapter类:
我想将xsd:date类型映射到Joda-Time LocalDate对象,并且读取 here,here和 here,我创建了以下DateAdapter类:
public class DateAdapter extends XmlAdapter<String,LocalDate> { private static DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd"); public LocalDate unmarshal(String v) throws Exception { return fmt.parseLocalDate(v); } public String marshal(LocalDate v) throws Exception { return v.toString("yyyyMMdd"); } }
<jaxb:globalBindings> <jaxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date" parseMethod="my.classes.adapters.DateAdapter.unmarshal" printMethod="my.classes.adapters.DateAdapter.marshal" /> </jaxb:globalBindings>
问题是,当我尝试maven编译我的项目,它失败,并出现以下错误:
[ERROR] \My\Path\MyProject\target\generated-sources\xjc\my\classes\generated\Adapter1.java:[20,59] non-static method unmarshal(java.lang.String) cannot be referenced from a static context [ERROR] \My\Path\MyProject\target\generated-sources\xjc\my\classes\generated\Adapter1.java:[24,59] non-static method marshal(org.joda.time.LocalDate) cannot be referenced from a static context
…这是事情变得奇怪的地方.
JAXB生成一个类Adapter1,其中包含以下内容:
public class Adapter1 extends XmlAdapter<String,LocalDate> { public LocalDate unmarshal(String value) { return (my.classes.adapters.DateAdapter.unmarshal(value)); } public String marshal(LocalDate value) { return (my.classes.adapters.DateAdapter.marshal(value)); } }
….这是编译错误的根源.
现在我的问题是:
>我的适配器覆盖XmlAdapter,我不能使方法静态….我如何避免这个?
>我可以避免一代Adapter1.class吗?也许使用包级注释XmlJavaTypeAdapters,如果是,我该怎么做呢? (JAXB生成一个自己的package-info.java ….)
希望我把我的情况清楚了
谢谢
解决方法
您不需要扩展XmlAdapter.
只需在POJO上创建静态方法即可.
例:
public class DateAdapter { private static DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd"); public static LocalDate unmarshal(String v) throws Exception { return fmt.parseLocalDate(v); } public static String marshal(LocalDate v) throws Exception { return v.toString("yyyyMMdd"); } }