1

I have two classes

    class First{
      private Date date;

      public Date getDate(){
        return date;
      }
      ...
    }

and

class Second extends First{
    @XmlAttribute
    @XmlJavaTypeAdapter(value = DateAdapter.class, type = Date.class)
    public Date getDate() {
        return super.getDate();
    }
}

Where DateAdapter just translates Date to Long and back.
I'm serializing an instance of the Second class and it seems to be that DateAdapter is ignored. I mean I get string "2013-05-22T13:32:40.664" instead of its Long representation.

If I'll move the @XmlJavaTypeAdapter annotation to the First class, it works OK, but my problem is that First can't be modified and that is basically the reason I created the wrapper class Second.

How can I make XmlJavaTypeAdapter be recognized?

4

1 回答 1

1

您可以使用EclipseLink JAXB (MOXy)的外部绑定文件为无法修改的类提供元数据:

oxm.xml

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="com.example.foo">
    <java-types>
        <java-type name="First">
            <java-attributes>
                <xml-element java-attribute="date">
                    <xml-java-type-adapter value="com.example.foo.DateAdapter"/>
                </xml-element>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

演示

然后,您可以JAXBContext使用指定元数据位置的属性来引导您:

import java.util.*;
import javax.xml.bind.JAXBContext;

import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "com/example/foo/oxm.xml");
        JAXBContext jc = JAXBContext.newInstance(new Class[] {First.class, Second.class}, properties);
    }

}

了解更多信息

于 2013-05-22T10:53:02.910 回答