我正在尝试结合 JAXB(Hibernate 在 dom4j 中提供)、Hibernate(4.1.3)和 Eclipse(4.2)插件。
我的“核心”插件包含一个 XMLUserType,它接受一个给定的 pojo(用 @XmlRootElement 和其余的注释;来自另一个插件)并将其转换为 XML,反之亦然。这段代码可以很好地进行解组( cls 是由参数给定的每个字符串的类:
public Object fromXMLString(final String xml) {
if (null != xml) {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(cls.getClassLoader());
final JAXBContext jc = JAXBContext.newInstance(cls);
final Unmarshaller unmarshaller = jc.createUnmarshaller();
final StreamSource sr = new StreamSource(new StringReader(xml));
final JAXBElement<?> element = unmarshaller.unmarshal(sr, cls);
return cls.cast(element.getValue());
} catch (final JAXBException e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
return null;
}
/** {@inheritDoc} */
@Override
public void setParameterValues(final Properties parameters) {
final String clsName = (String) parameters.get("ClassType");
try {
this.cls = Thread.currentThread().getContextClassLoader().loadClass(clsName);
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
不幸的是,编组失败了,我不知道为什么。
public static Document convertToXML(final Object pojo, final Class<?> type) throws SystemException {
Document ret = null;
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(type.getClassLoader());
final JAXBContext jc = JAXBContext.newInstance(type);
final Marshaller marshaller = jc.createMarshaller();
final DocumentResult dr = new DocumentResult();
marshaller.marshal(pojo, dr);
final Document document = dr.getDocument();
ret = document;
} catch (final JAXBException e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return ret;
}
是否设置了 ClassLoader 无关紧要。它总是失败并出现以下异常:
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type
"packagingdetails.PackagingDetails" as an element because it is missing an
@XmlRootElement annotation
我相信原因是以下原因之一: 1. 注释由代理表示,因此无法解析 2. ClassLoader 制造麻烦......
关于 1.:我注意到(我试图用它来获取 XmlRootElement 的名称来创建 JAXBElement,但这似乎不可行......;我的 JAXBType 应该保持通用)
final Annotation[] annotations = type.getAnnotations();
XmlRootElement xmlRootElement = null;
for (final Annotation a : annotations) {
if (XmlRootElement.class.isAssignableFrom(a.annotationType())) {
xmlRootElement = (XmlRootElement) a;
break;
}
}
总是失败...
有没有人有任何想法???
谢谢马蒂亚斯