JAXBException: class java.util.ArrayList nor any of its super class is known to this context

This exception occurs when you are using JAXB to marshal a Java object (collection type) to xml format. The stack trace looks like this: 1. Reason The above exception occurs because JAXB always expects a @XmlRootElement annotation on the entity, it gets to marshal. This is mandatory and …

This exception occurs when you are using JAXB to marshal a Java object (collection type) to xml format. The stack trace looks like this:

Exception in thread "main" jakarta.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
	at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(Unknown Source)
	at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source)
	at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)
	at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)
	at jakarta.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
	at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58)
Random exceptions
Random exceptions

1. Reason

The above exception occurs because JAXB always expects a @XmlRootElement annotation on the entity, it gets to marshal. This is mandatory and can not be skipped. This @XmlRootElement annotation is required to get metadata from the root element of XML marshalled from a Java object.

ArrayList class OR any java collection class does not have any JAXB annotations on it. Due to this JAXB is unable to parse any such java objects and raises this error.

2. The solution is to a Create Wrapper Class

This is a recommended approach because it gives you the flexibility to add/remove fields in the future e.g. size attribute.

@XmlRootElement(name = "employees")
@XmlAccessorType(XmlAccessType.FIELD)
class Employees {

  @XmlElement(name = "employee")
  private List<Employee> employees = new ArrayList<>();

  public List<Employee> getEmployees() {
    return employees;
  }

  public void setEmployees(List<Employee> employees) {
    this.employees = employees;
  }
}

Now you can use this class as below:

Employees employees = new Employees();

//Add the employees in list
Employee emp1 = new Employee(1, "Lokesh", "Gupta", null, null);
Employee emp2 = new Employee(1, "John", "McLean", null, null);
employees.getEmployees().add(emp1);
employees.getEmployees().add(emp2);

//Write to XML
JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

//Marshal the employees list in console
jaxbMarshaller.marshal(employees, System.out);

//Marshal the employees list in file
jaxbMarshaller.marshal(employees, new File("out.xml"));

The program output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employee>
        <id>1</id>
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
    </employee>
    <employee>
        <id>1</id>
        <firstName>John</firstName>
        <lastName>McLean</lastName>
    </employee>
</employees>

See the complete example in this post: Marshalling example java ArrayList or Set

Happy Learning !!

Leave a Comment

  1. Thanks it worked for me object needs to be same as your @XmlRootElement(name=”studentList”),List studentList = new ArrayList(); and try to make it generic using your poja class

    package com.javainterviewpoint;

    import java.util.ArrayList;
    import java.util.List;

    import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement(name=”studentList”)
    public class StudentList
    {
    List studentList = new ArrayList();

    public List getStudentList()
    {
    return studentList;
    }

    public void setStudentList(List studentList)
    {
    this.studentList = studentList;
    }
    }

    Reply
  2. Hi,

    I have tried your solution, with a bit of modification to suit my use case. However, I am now getting a cast error in my soap: “java.lang.ClassCastException: acme.flight.soap.service.impl.FlightList cannot be cast to java.util.List”

    Please let me know if you can help with this and how I can solve it. I have pasted the class below.

    FlightList Class

    @XmlRootElement(name = “flights”)
    @XmlAccessorType(XmlAccessType.FIELD)
    public class FlightList {

    @XmlElement(name = "flight")
    protected List flights = null;

    public List getFlights() {
    return flights;
    }

    public void setFlights(List flights) {
    this.flights = flights;
    }

    }

    SoapImpl Class

    public List getFlightList(String startCity, String destCity, Date departDate, Date returnDate) {

    FlightList flightList = new FlightList();

    {
    flightList.setFlights(new ArrayList());

    Flight outbound = new Flight();
    Query q1 = em.createNamedQuery("Flight.findFiltered");
    q1.setParameter("startCity", startCity);
    q1.setParameter("targetCity", destCity);
    q1.setParameter("travelDate", departDate);

    outbound = (Flight) q1.getSingleResult();

    Flight inbound = new Flight();
    Query q2 = em.createNamedQuery("Flight.findFiltered");
    q2.setParameter("startCity", destCity);
    q2.setParameter("targetCity", startCity);
    q1.setParameter("travelDate", returnDate);

    inbound = (Flight) q2.getSingleResult();

    flightList.getFlights().add(inbound);
    flightList.getFlights().add(outbound);
    }
    return (List) flightList;

    }

    Reply
    • No worries, I have found a solution to my problem. I needed to convert my FlightList class into a list.

      These are the changes I did to make it work

      FlightList Class

      @XmlRootElement(name = “flights”)
      @XmlAccessorType(XmlAccessType.FIELD)
      public class FlightList extends ArrayList {

      }

      SoapImpl Class

      public List getFlightList(String startCity, String destCity, Date departDate, Date returnDate) {

      FlightList flightList = new FlightList();

       {
          Flight outbound = new Flight();
          Query q1 = em.createNamedQuery("Flight.findFiltered");
          q1.setParameter("startCity", startCity); 
          q1.setParameter("targetCity", destCity); 
                      q1.setParameter("travelDate", departDate);
      
          outbound = (Flight) q1.getSingleResult();
      
          Flight inbound = new Flight();
          Query q2 = em.createNamedQuery("Flight.findFiltered");
          q2.setParameter("startCity", destCity); 
          q2.setParameter("targetCity", startCity); 
                      q2.setParameter("travelDate", returnDate);
      
          inbound = (Flight) q2.getSingleResult();
      
          flightList.add(inbound);
          flightList.add(outbound);
      }       
      
          return flightList;
      

      }

      Reply
  3. Exception in thread “main” javax.xml.bind.JAXBException: Unable to create context
    – with linked exception:
    [java.lang.reflect.InvocationTargetException]
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:61)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:77)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:73)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:69)
    at com.ds.test.POTest.main(POTest.java:17)
    Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:59)
    … 4 more
    Caused by: java.lang.NoSuchMethodError: javax.xml.bind.annotation.XmlAccessorType.value()Ljavax/xml/bind/annotation/AccessType;
    at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.getAccessType(ClassInfoImpl.java:339)
    at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.getProperties(ClassInfoImpl.java:228)
    at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.getProperties(RuntimeClassInfoImpl.java:87)
    at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:127)
    at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
    at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
    at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
    at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.(RegistryInfoImpl.java:51)
    at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:232)
    at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:201)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:327)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:198)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:124)
    … 9 more

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.