JAXB binding file: XmlAdapters and package name

前端 未结 5 1017
渐次进展
渐次进展 2021-02-04 04:45

I have a binding file like this



        
5条回答
  •  遇见更好的自我
    2021-02-04 05:08

    The better way to use GlobalBinding is to specify explicit adapter instead of using this parse/print pair. For example, instead of the following:

    
    

    Instead, you should:

    
    

    Remember to add namespace for xjc:

    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
              jxb:extensionBindingPrefixes="xjc"
    

    The class LongAdapter would be like this:

    public class LongAdapter
    extends XmlAdapter
    {
    
    
    public Long unmarshal(String value) {
        return your_util_class.parseLong(value);
    }
    
    public String marshal(Long value) {
        return your_util_class.print(value);
    }
    
    }
    

    In this way, since you specified adapter classes explicitely, jaxb won't generate default adapters with the default package name org.w3._2001.xmlschema.

    It is very important to avoid to use the default package name org.w3._2001.xmlschema. Taking one example, if you have one project A and one project B, and both of them have some schema and bindings. In the old way, both of them generate adapters with exactly the same full qualified names, e.g. org.w3._2001.xmlschema.Adapter1. However, this adapter might be for Long in project A and for Integer in project B. Then, let's say you have a downstream project C using both A and B. Now the problem gets nasty. If C needs to use Adapter1, you cannot predict the used one is from A for Long or from B for Integer. Then, your application C might work fine in some time but maybe fail in a strange way in some other situations. If this happens, the type exception would be like:

    org.w3._2001.xmlschema.Adapter1 is not applicable to the field type java.lang.Double...
    

    The solution mentioned by Roy Truelove seems not working when I tried it in my environment with maven-jaxb2-plugin even if the theory is correct.

提交回复
热议问题