本文介绍了@XmlRootElement和< T extends Serializable>抛出IllegalAnnotationExceptions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我编组此类的一个实例时...
When I marshall an instance of this class ...
@XmlRootElement
public static class TestSomething<T extends Serializable> {
T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
...抛出以下异常...
... the following Exception is thrown ...
com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.io.Serializable is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at java.io.Serializable
at public java.io.Serializable TestSomething.getId()
at TestSomething
java.io.Serializable does not have a no-arg default constructor.
this problem is related to the following location:
at java.io.Serializable
at public java.io.Serializable TestSomething.getId()
at TestSomething
如何避免这种情况(不将类型参数更改为< T>
)?
How can I avoid this (without changing the type parameter to something like <T>
)?
推荐答案
您需要使用@XmlElement和@XmlSchemaType的组合:
You need to use a combination of @XmlElement and @XmlSchemaType:
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
@XmlRootElement
public class TestSomething<T extends Serializable> {
T id;
@XmlElement(type=Object.class)
@XmlSchemaType(name="anySimpleType")
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
如果您运行以下内容:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(TestSomething.class);
TestSomething<Integer> foo = new TestSomething<Integer>();
foo.setId(4);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
您将获得:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testSomething>
<id xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:int">4</id>
</testSomething>
这篇关于@XmlRootElement和< T extends Serializable>抛出IllegalAnnotationExceptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!