views:

36

answers:

1

Currently, JAXB is creating a point class from the xml schema I have specified. However, I would prefer it to use the existing java.awt.Point class. And for any other types I have defined to use and import java.awt.Point too.

Here is my point code:

<xs:complexType name="point">
  <xs:sequence>
    <xs:element name="x" type="xs:int" />
    <xs:element name="y" type="xs:int" />
  </xs:sequence>
</xs:complexType>

Is this possible?

+3  A: 

I don't know if my solution is very elegant but I believe it works as you demand.

Consider class Test with a property p of type java.awt.Point:

@XmlRootElement
public class Test {
    @XmlElement
    @XmlJavaTypeAdapter(PointAdapter.class)
    public Point p;
}

The class PointAdapter is as follows:

class PointAdapter extends XmlAdapter<String, Point> {

    @Override
    public String marshal(Point v) throws Exception {
        return String.format("%d;%d", v.x, v.y);
    }

    @Override
    public Point unmarshal(String v) throws Exception {
        String[] coords = v.split(";");
        return new Point(Integer.parseInt(coords[0]), Integer.parseInt(coords[1]));
    }

}

If you don't create your Java classes by hand but let them generate by xjc there is a possibility to specify the XmlAdapter in the schema too; either through a seperate binding file that you can specify with the -b option of xjc or embedded in your XSD. Personally I prefer the first solution as this keeps the schema clean. Since it has been a while since I played with this I refer you to the JAXB documentation (look for MyDatatypeConverter; this should be the most relevant part).

musiKk
Thanks! I'll give it a shot.
fli