【发布时间】:2019-03-08 23:08:33
【问题描述】:
我对 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] \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....)
希望我能说明我的情况。
谢谢
【问题讨论】:
标签: java binding annotations jaxb