开发者

JAXB: setting complexTypes to use existing java classes

开发者 https://www.devze.com 2023-01-14 17:29 出处:网络
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 o开发者_开发问答ther types I have defin

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 o开发者_开发问答ther 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消