Java – JAXB, custom binding, adapter1 Class and joda time
I have a problem. JAXB is generating binding classes for XML schema (I can't modify them for precision)
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"); } }
I add 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>
The problem is that when I try to compile my project with maven, 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
... this is where things get strange JAXB generates a class adapter1, which contains the following contents:
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)); } }
…. This is the source of compilation errors
Now my question is:
>My adapter overrides xmladapter, I can't make the method static How can I avoid this? > I can avoid generation adapter 1 Class? Maybe use package level annotation xmljavatypeadapters. If so, what should I do? (JAXB generates its own package info. Java...)
I hope I've made my situation clear. Thank you
Solution
You do not need to extend xmladapter
Just create a static method on the POJO
Example:
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"); } }