JAXB extend generated code with extended object factory
I've got some JAXB generated beans which are in an hierarchical structure, eg one bean holds a list of other beans. Now I want to extend some child element and also the parent element holding the extended children.
My ParentEx
implements some other interface IParent
which is expected to return an Collection<IChild>
. My ChildEx
implements IChild
. Can I return a (Collection<IChild>)super.getChild()
when super.getChild()
returns List<Child>
? Or is there a nicer way of doing this?
Child
and Parent
are JAXB generated beans ChildEx
and ParentEx
are my own beans for mapping the JAXB beans to the given interfaces. Both beans override the ObjectFactory
IChild
and IParent
are the interfaces needed from some other library Edit: Eclipse doesn't even let my cast from List<Child>
to List<ChildEx>
so I have to add some ugly intermediary wildcard cast (List<ChildEx>)(List<?>)super.getChild()
This should work:
return new ArrayList<IChild>( childExList );
or (not pretty but avoids wildcard cast):
return Arrays.asList( childExList.toArray(new IChild[]{}) );
In Java it's not type safe to cast Generic<Type>
to Generic<SuperType>
which is what you are trying to do by casting List<Child>
to Collection<IChild>
. Imagine a List<Integer>
being cast to List<Object>
, that would allow you to put anything into the list, not just Integer
or subtypes.
It is safe to cast Generic<Type>
to GenericSuperType<Type>
as user268396 points out in the comment.
You are going to need to copy the List<Child>
into some new collection eg
List<Child> sourceList = ...
List<IChild> targetList = new ArrayList<IChild>();
Collections.copy(targetList, sourceList);
You can then return targetList
which can be implicitly cast to Collection<IChild>
上一篇: Java中的XOR神经网络
下一篇: JAXB使用扩展对象工厂扩展生成的代码