如何使用JAXB使用私有字段编组/解组Java对象 [英] How to marshal/unmarshal Java objects with private fields using JAXB

查看:158
本文介绍了如何使用JAXB使用私有字段编组/解组Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JAXB API的基础知识,但我遇到了一些我想做的事情,我不确定它是否真的可行。详细信息如下:

I know the basics of the JAXB API, but I am stuck with something I am trying to do, and I am not sure whether it is actually possible. Details are as follows:

我有一个名为 Book 的类,其中包含2个 public 类型为String的实例变量:

I have a class called Book with 2 public instance variables of type String:

@XmlRootElement(name="book")
public class Book
{
    public String title;
    public String author;

    public Book() {
    }
}



<我有一个名为书店的另一个类,其中包含1个类型为ArrayList的 public 实例变量:

I have a another class called Bookshop with 1 public instance variable of type ArrayList:

@XmlRootElement(name="bookshop")
public class Bookshop
{
    @XmlElementWrapper(name="book_list")
    @XmlElement(name="book")
    public ArrayList<Book> bookList;

    public Bookshop() {
        this.bookList = new ArrayList<>();
    }
}

注意:包裹声明和导入将被删除以便节省空间。

Note: package declaration and imports are removed in order to save space.

这两个类可以工作,我得到的输出XML是这样的:

These two classes work and the output XML I get is something like:

<bookshop>
    <book_list>
        <book>
            <title>Book 1</title>
            <author>Author 1</author>
        </book>
        <book>
            <title>Book 2</title>
            <author>Author 2</author>
        </book>
    </book_list>
</bookshop>

据我所知,实例变量需要声明为public才能使其类可序列化。或者,实例变量可以声明为私有,但在这种情况下需要访问器和更改器。

As far as I know, instance variables need to be declared public in order for its class to be serialisable. Or, instance variables can be declared private, but accessors and mutators are needed in that case.

我不喜欢声明实例变量public;我喜欢使用存取器和变换器。即便如此,我希望我的一些字段是只读的,即没有变异器。但是JAXB似乎需要为每个要编组/解组的字段配置访问器和更改器。我想知道是否有任何办法解决这个问题?

I don't like declaring instance variables public; I like using accessors and mutators. Even then, I want some of my fields to be read-only, i.e., no mutator. But JAXB seems to require both accessors and mutators for each field you want to marshal/unmarshal. I was wondering if there is any way around this?

推荐答案

在任何情况下都应保持字段为私有。您有两个绑定到字段的选项

You should keep your fields private in any case. You have 2 options binding to fields

1)使用XmlElement或XmlAttribute批注对字段进行批注

1) annotate your fields with XmlElement or XmlAttribute annotation

@XmlRootElement(name="book")
public class Book {
    @XmlElement
    private String title;
    ...

2)使用@XmlAccessorType(XmlAccessType.FIELD)注释你的类

2) annotate your class with @XmlAccessorType(XmlAccessType.FIELD)

    @XmlRootElement(name="book")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Book {
         private String title;
         ...

这篇关于如何使用JAXB使用私有字段编组/解组Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆