gpt4 book ai didi

java - @XmlRootElement 和 抛出 IllegalAnnotationExceptions

转载 作者:行者123 更新时间:2023-11-30 11:57:32 26 4
gpt4 key购买 nike

当我整理这个类的一个实例时......

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

关于java - @XmlRootElement 和 <T extends Serializable> 抛出 IllegalAnnotationExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com