2

当我编组这个类的一个实例时......

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

4

3 回答 3

1

您需要结合使用@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>
于 2010-09-20T12:54:27.667 回答
0

是一个如何使用 JAXB 接口的指南。

JAXB 需要具体的类,因为它必须在从 XML 编组时实例化它们。如果T不是具体的类,它就不能被实例化。

于 2010-09-18T21:54:20.950 回答
0

添加@XmlAnyElement到“id”字段(以及@XmlAccessorType(XmlAccessType.FIELD)类级别的注释)或为 getter 添加相同的字段将解决此问题。(但它使 xml 元素的 type any。)

于 2017-12-26T10:15:24.393 回答