Understanding JAXB: Java Binding Customization
Subject:   Polymorphic behaviour problem
Date:   2003-12-26 12:32:10
From:   hashimisayed
Response to: Polymorphic behaviour problem

I understand your point. Even if you derive from a common base class that only allows you to say shape.draw() without having to know the particular derived shape type. But what happens when draw is called on the shape? The base class of all shapes can define a draw method but the implementation of the shapes have to implement the method. The problem is that JAXB generates the implementation. The solution is to provide a base interface for all the shapes and extend the JAXB generated implementation classes with your own custom implementations. Let me give you the details. I'll keep using the Shape example.

  1. Write the base interface for all the shapes(e.g., MyShape). MyShape defines a draw() method.
  2. Customize JAXB so that you extend the JAXB generated implementation classes.

************* Step (1) ****************

// the base interface for all shapes
public interface MyShape
void draw();

************ Step (2) *****************

// customize JAXB so that it uses your implementation classes.

// for all the shapes, add implementation classes. Here is an example for the Square,
<xs:complextType name="Square">
<jaxb:class implClass="MySquareImpl" />


// use JAXB to generated interfaces and classes as usual.

// Now you need to write the implementation classes. The implementation classes need to implement MyShape and extend the JAXB generated implementation class. Here is an example for the Square.

// at this point, you have a base interface and JAXB has generated
// interfaces and implementations for Circle, Rectangle, and Square.

public class MySquareImpl extends SquareImpl implements MyShape
public void draw()
// Note that you can get to all of the square's
// Members because JAXB generated protected members for SquareImpl
System.out.println("drawing square");

// Now when iterating through the shapes, we can simple call draw().

List shapes = widgets.getShapes();
Iterator it=shapes.iterator();
MyShape shape = (MyShape);