@XmlRootElement 和 抛出 IllegalAnnotationExceptions

2023-12-21

当我编组此类的实例时......

@XmlRootElement
public static class TestSomething<T extends Serializable> {

    T id;

    public T getId() {
        return id;
    }

    public void setId(T id) {
        this.id = id;
    }
}

...抛出以下异常...

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


您需要使用 @XmlElement 和 @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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@XmlRootElement 和 抛出 IllegalAnnotationExceptions 的相关文章

随机推荐