加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

…这是事情变得奇怪的地方.
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");
    }
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读