本文介绍了JAXB,自定义绑定,Adapter1.class和乔达时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JAXB产生了对XML模式(对于precision的缘故,我不能修改)绑定类方式有问题。
我想映射的xsd:日期类型到乔达时间对象LOCALDATE和,读的,here和here,我创建了以下DateAdapter类:

I have a problem with the way JAXB is generating the bound classes for an XML schema (which, for sake of precision, I cannot modify).I want to map a xsd:date type to a Joda-time LocalDate object and, reading here, here and here, I created the following DateAdapter class:

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");
    }
}

和我添加以下到我的全局绑定文件:

And I added the following to my global binding file:

  <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编译我的项目时,出现以下错误:

The problem is that, when I try to maven compile my project, it fails with the following error:

[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生成一个类适配器1包含以下内容:

...and this is where things get weird.JAXB generates a class Adapter1 that contains the following:

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));
    }

}

... ...这是编译错误的来源。

....which is the source of the compilation error.

现在,我的问题是:


  • 会被我的适配器覆盖XmlAdapter,我不能让这些方法静态....我怎么避免这种情况?

  • 我能避免Adapter1.class的产生完全?也许使用包级注释XmlJavaTypeAdapters,如果是这样,我怎么办呢?究竟(JAXB已经产生了自己的package-info.java ....)

希望我做了我的情况不清楚。结果
谢谢

Hope I made my situation clear.
Thanks

推荐答案

您不需要延长 XmlAdapter

只需创建一个POJO静态方法,它会正常工作。

Just create static methods on a POJO and it will work.

例如:

 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");
    }
 }

这篇关于JAXB,自定义绑定,Adapter1.class和乔达时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:38