Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB extend generated code with extended object factory - explicit casts good?

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 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()

like image 762
Franz Kafka Avatar asked Mar 12 '12 09:03

Franz Kafka


2 Answers

This should work:

return new ArrayList<IChild>( childExList );

or (not pretty but avoids wildcard cast):

return Arrays.asList( childExList.toArray(new IChild[]{}) );
like image 199
Andrejs Avatar answered Oct 01 '22 18:10

Andrejs


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>

like image 22
matthewSpleep Avatar answered Oct 01 '22 18:10

matthewSpleep