我正在尝试将颜色编组/解组为 XML。JAXB 项目具有通过 XmlJavaTypeAdapter https://jaxb.java.net/guide/XML_layout_and_in_memory_data_layout.html执行此操作的示例代码。
编组工作正常,输出是我所期望的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beanWithColor>
<foreground>#ff0000ff</foreground>
<name>CleverName</name>
</beanWithColor>
但是,当尝试从 XML 转到对象时,永远不会调用 unmarshal 方法。任何人都可以提供有关原因的见解吗?解组后,前景色为空,我已经用我的调试器确认 unmarshal 永远不会被调用:
BeanWithColor{foreground=null, name='CleverName'}
SCCE:
@XmlRootElement
public class BeanWithColor {
private String name;
private Color foreground;
public BeanWithColor() {
}
public BeanWithColor(Color foreground, String name) {
this.foreground = foreground;
this.name = name;
}
@XmlJavaTypeAdapter(ColorAdapter.class)
public Color getForeground() {
return this.foreground;
}
public void setForeground(Color foreground) {
this.foreground = foreground;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BeanWithColor{");
sb.append("foreground=").append(foreground);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
public static void main(String[] args) {
BeanWithColor bean = new BeanWithColor(Color.blue, "CleverName");
try {
StringWriter writer = new StringWriter(1000);
JAXBContext context = JAXBContext.newInstance(BeanWithColor.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.marshal(bean, writer);
System.out.println("Marshaled XML: " + writer);
final Unmarshaller unmarshaller = context.createUnmarshaller();
BeanWithColor beanWithColor = (BeanWithColor) unmarshaller.unmarshal(new StringReader(writer.toString()));
System.out.println("beanWithColor = " + beanWithColor);
} catch (JAXBException e) {
e.printStackTrace();
}
}
static class ColorAdapter extends XmlAdapter<String, Color> {
public Color unmarshal(String s) {
return Color.decode(s);
}
public String marshal(Color color) {
return '#' + Integer.toHexString(color.getRGB());
}
}
}