I've got some JAXB generated beans which are in an hierarchical structure, e.g. 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 beansChildEx 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 libraryEdit: 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 e.g.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With