title: Is it possible to programmatically configure JAXB?
body: <p>Say I have two JavaBeans <code>Person</code> and <code>Address</code>. </p>
  
  <p>If I create a list of Person objects, I'd like to marshal to something like this: </p>
  
  <pre><code>&lt;persons&gt;
    &lt;person&gt;...&lt;/person&gt;
  &lt;/persons&gt;
  </code></pre>
  
  <p>It's possible to use the technique described here: 
  <a href="https://stackoverflow.com/questions/1603404/using-jaxb-to-unmarshal-marshal-a-liststring">Using JAXB to unmarshal/marshal a List&lt;String&gt;</a></p>
  
  <p>By annotating JaxbList with <code>@XmlRootElement(name = "persons")</code> and <code>@XmlElement(name = "person")</code>, then it's possible to marshal to the XML above. </p>
  
  <p>But, it'd be nice to be able to reuse the same <code>JaxbList&lt;T&gt;</code> class to also marshal a list of <code>Address</code> objects. And in reality, I will have many other types of beans. I can go with something like: </p>
  
  <pre><code>&lt;list&gt;
     &lt;item xsi:type="person" xmlns:xsi="http://www.w2.org/2001/XmlSchema-instance"&gt;&lt;/item&gt;
  &lt;/list&gt;
  </code></pre>
  
  <p>But, ideally, it'd be nice to have it replace "list" with the plural version of class name and "item" with the class name. </p>
  
  <p>So, is it possible to programmatically configure the JaxbContext or something during runtime and essentially set the value of the <code>name</code> inside <code>@XmlRootElement</code> and <code>@XmlElement</code>?</p>
  
  <p>Or any other way to get this working without having to write a separate implementation of <code>JaxbList</code> for every bean type? Maybe XmlJavaTypeAdapter can achieve this sort of thing?</p>
  
  <p><strong>Update</strong> 
  @Blaise Doughan's solution accepted below works great. For my use case, I needed to go straight from Java object to XML, here's what worked (note this is not my full implementation, it's sort of just pseudo code for demonstration): </p>
  
  <pre><code>    //JAXBContext is thread safe and so create it in constructor or 
      //setter or wherever:
      ... 
      JAXBContext jc = JAXBContext.newInstance(Wrapper.class, clazz);
      ... 
  
      public String marshal(List&lt;T&gt; things, Class clazz) {
  
        //configure JAXB and marshaller     
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  
        //Create wrapper based on generic list of objects
        Wrapper&lt;T&gt; wrapper = new Wrapper&lt;T&gt;(things);
        JAXBElement&lt;Wrapper&gt; wrapperJAXBElement = new JAXBElement&lt;Wrapper&gt;(new QName(clazz.getSimpleName().toLowerCase()+"s"), Wrapper.class, wrapper);
  
        StringWriter result = new StringWriter();
        //marshal!
        m.marshal(wrapperJAXBElement, result);
  
        return result.toString();
  
      }
  </code></pre>