JAXB Marshalling and Generics

后端 未结 5 1040
天涯浪人
天涯浪人 2020-12-17 19:29

I am trying to use JAXB\'s introspection to marshall and unmashall some existing domain objects marked up with JAXB annotations. Most things work as expected, but I am havin

5条回答
  •  天命终不由人
    2020-12-17 19:49

    You could write a custom adapter (not using JAXB's XmlAdapter) by doing the following:

    1) declare a class which accepts all kinds of elements and has JAXB annotations and handles them as you wish (in my example I convert everything to String)

    @YourJAXBAnnotationsGoHere
    public class MyAdapter{
    
      @XmlElement // or @XmlAttribute if you wish
      private String content;
    
      public MyAdapter(Object input){
        if(input instanceof String){
          content = (String)input;
        }else if(input instanceof YourFavoriteClass){
          content = ((YourFavoriteClass)input).convertSomehowToString();
        }else if(input instanceof .....){
          content = ((.....)input).convertSomehowToString();
        // and so on
        }else{
          content = input.toString();
        }
      }
    }
    
    // I would suggest to use a Map,IMyObjToStringConverter> ...
    // to avoid nasty if-else-instanceof things
    

    2) use this class instead of E in your to-be-marshalled class

    NOTES

    • Of course this would not work for complex (nested) data structures.
    • You have to think how to unmarshall this back again, could be more tricky. If it's too tricky, wait for a better proposal than mine ;)

提交回复
热议问题