title: How to marshal/unmarshal Java objects with private fields using JAXB
body: <p>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:</p>
  
  <p>I have a class called <strong>Book</strong> with 2 <em>public</em> instance variables of type String:</p>
  
  <pre><code>@XmlRootElement(name="book")
  public class Book
  {
      public String title;
      public String author;
  
      public Book() {
      }
  }
  </code></pre>
  
  <p>I have a another class called <strong>Bookshop</strong> with 1 <em>public</em> instance variable of type ArrayList:</p>
  
  <pre><code>@XmlRootElement(name="bookshop")
  public class Bookshop
  {
      @XmlElementWrapper(name="book_list")
      @XmlElement(name="book")
      public ArrayList&lt;Book&gt; bookList;
  
      public Bookshop() {
          this.bookList = new ArrayList&lt;&gt;();
      }
  }
  </code></pre>
  
  <p>Note: package declaration and imports are removed in order to save space.</p>
  
  <p>These two classes work and the output XML I get is something like:</p>
  
  <pre><code>&lt;bookshop&gt;
      &lt;book_list&gt;
          &lt;book&gt;
              &lt;title&gt;Book 1&lt;/title&gt;
              &lt;author&gt;Author 1&lt;/author&gt;
          &lt;/book&gt;
          &lt;book&gt;
              &lt;title&gt;Book 2&lt;/title&gt;
              &lt;author&gt;Author 2&lt;/author&gt;
          &lt;/book&gt;
      &lt;/book_list&gt;
  &lt;/bookshop&gt;
  </code></pre>
  
  <p>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.</p>
  
  <p>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?</p>