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
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<Class<?>,IMyObjToStringConverter> ...
// to avoid nasty if-else-instanceof things
2) use this class instead of E in your to-be-marshalled class
NOTES
How about
public class Range<**E extends Number**> implements Serializable { ...
Number is a class
I bet JAXB knows default marshalling/unmarshalling rules for Number
For unmarshalling to specific type, you need XmlAdapter as I described here: JAXB inheritance, unmarshal to subclass of marshaled class
Actually, it is not quite clear to me why this would not work. It seems like JAXB should be able to resolve specific subtype correctly: if (and only if!) this type is NOT the root type (which it is not as per your description). I mean, it is just a Bean; so if bean with T replaced with direct type works, so should generic version iff using sub-classing to bind types (as is done in example).
So perhaps it could be a bug in implementation?
So it looks like the problem is the erasure of E
on start
and end
is Comparable
. If it can't handle interfaces you could try Object
, but I would hope it complains at that too (either now or later). Possibly you could make Range
abstract and specialise it for each specific E
. I should know more about JAXB.
Try something like Simple XML Serialization it comes with support for generic types in XML elements with a number of annotations such as @Element and @ElementList. The programming model is very similar, but simpler than JAXB.