Java:调用JAXBContext.newInstance()

时间:2017-12-19 13:56:23

标签: java xml jaxb

我有一个班级:

import javax.xml.bind.annotation.*;

@XmlRootElement
class Plansza 
{
    String tura;

    String b0;
    String b1;
    String b2;

    String b3;
    String b4;
    String b5;

    String b6;
    String b7;
    String b8;


    @XmlElement
    public String getTura()
    {
        return this.tura;
    }

    public void setTura(String tura)
    {
        this.tura = tura;
    }

    @XmlElement
    public String getB0()
    {
        return this.b0;
    }

    public void setB0(String b0)
    {
        this.b0 = b0;
    }

    @XmlElement
    public String getB1()
    {
        return this.b1;
    }

    public void setB1(String b1)
    {
        this.b1 = b1;
    }

    @XmlElement
    public String getB2()
    {
        return this.b2;
    }

    public void setB2(String b2)
    {
        this.b2 = b2;
    }

    @XmlElement
    public String geB3()
    {
        return this.b3;
    }

    public void setB3(String b3)
    {
        this.b3 = b3;
    }

    @XmlElement
    public String getB4()
    {
        return this.b4;
    }

    public void setB4(String b4)
    {
        this.b4 = b4;
    }

    @XmlElement
    public String getB5()
    {
        return this.b5;
    }

    public void setB5(String b5)
    {
        this.b5 = b5;
    }

    @XmlElement
    public String getB6()
    {
        return this.b6;
    }

    public void setB6(String b6)
    {
        this.b6 = b6;
    }

    @XmlElement
    public String getB7()
    {
        return this.b7;
    }

    public void setB7(String b7)
    {
        this.b7 = b7;
    }

    @XmlElement
    public String getB8()
    {
        return this.b8;
    }

    public void setB8(String b8)
    {
        this.b8 = b8;
    }   
}

我希望序列化为XML并从XML文件中读取此类。 但是,当我创建上下文时:

JAXBContext context = JAXBContext.newInstance(Plansza.class);

它会抛出 IllegalAnnotationsException

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
JAXB annotation is placed on a method that is not a JAXB property
    this problem is related to the following location:
        at @javax.xml.bind.annotation.XmlElement(name=##default, namespace=##default, type=class javax.xml.bind.annotation.XmlElement$DEFAULT, required=false, defaultValue=, nillable=false)
        at Plansza

我尝试添加构造函数,但似乎没有任何工作,stil得到相同的异常。

编辑按要求上传整个Plansza类代码。

1 个答案:

答案 0 :(得分:1)

一种选择是将以下注释添加到类

@XmlAccessorType(XmlAccessType.FIELD)

然后将@XmlElement注释移动到这样的变量上。

@XmlElement
String tura = null;

然后,这将使用带注释的变量来生成XML