java – JAXB,自定义绑定,Adapter1.class和Joda-time
发布时间:2020-12-14 16:25:29 所属栏目:Java 来源:网络整理
导读:我有一个问题,JAXB正在为 XML模式生成绑定类(为了精度,我无法修改). 我想将xsd:date类型映射到Joda-Time LocalDate对象,并且读取 here,here和 here,我创建了以下DateAdapter类: public class DateAdapter extends XmlAdapterString,LocalDate { private st
我有一个问题,JAXB正在为
XML模式生成绑定类(为了精度,我无法修改).
我想将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] MyPathMyProjecttargetgenerated-sourcesxjcmyclassesgeneratedAdapter1.java:[20,59] non-static method unmarshal(java.lang.String) cannot be referenced from a static context [ERROR] MyPathMyProjecttargetgenerated-sourcesxjcmyclassesgeneratedAdapter1.java:[24,59] non-static method marshal(org.joda.time.LocalDate) cannot be referenced from a static context …这是事情变得奇怪的地方. 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,我不能使方法静态….我如何避免这个? 希望我把我的情况清楚了 解决方法
您不需要扩展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"); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |