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

どうすればこれを回避できますか(typeパラメーターをのようなものに変更せずに<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 に答える