# [已解决]:javax.xml.bind.JAXBException:此上下文已知类 java.util.ArrayList 或其任何超类 > 原文: [https://howtodoinjava.com/jaxb/solved-javax-xml-bind-jaxbexception-class-java-util-arraylist-nor-any-of-its-super-class-is-known-to-this-context/](https://howtodoinjava.com/jaxb/solved-javax-xml-bind-jaxbexception-class-java-util-arraylist-nor-any-of-its-super-class-is-known-to-this-context/) 当您使用 [**JAXB**](//howtodoinjava.com/category/frameworks/jaxb/ "JAXB tutorials") 将 Java 对象(集合类型)编组为 xml 格式时,会发生此异常。 堆栈跟踪如下所示: ```java Exception in thread "main" javax.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 javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source) at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58) ``` ![Random exceptions](img/bfcee52d8f51b09dd5024f261008e635.png) Random exceptions ## 原因 发生上述异常是因为 JAXB 总是期望实体上有一个@XmlRootElement 注解,它会编组。 这是强制性的,不能跳过。 需要@XmlRootElement 注解才能从 Java 对象编组的 XML 根元素中获取元数据。 ArrayList 类或任何 Java 集合类都没有任何 JAXB 注解。 由于这个原因,JAXB 无法解析任何此类 java 对象,并引发此错误。 ## 解决方案:创建包装器类 建议您使用此方法,因为它可以让您灵活地在将来(例如)添加/删除字段 尺寸属性。 ```java @XmlRootElement(name = "employees") @XmlAccessorType (XmlAccessType.FIELD) public class Employees { @XmlElement(name = "employee") private List employees = null; public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } } ``` 现在,您可以按以下方式使用此类: ```java static Employees employees = new Employees(); static { employees.setEmployees(new ArrayList()); Employee emp1 = new Employee(); emp1.setId(1); emp1.setFirstName("Lokesh"); emp1.setLastName("Gupta"); emp1.setIncome(100.0); Employee emp2 = new Employee(); emp2.setId(2); emp2.setFirstName("John"); emp2.setLastName("Mclane"); emp2.setIncome(200.0); employees.getEmployees().add(emp1); employees.getEmployees().add(emp2); } private static void marshalingExample() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(employees, System.out); } Output: 1 Lokesh Gupta 100.0 2 John Mclane 200.0 ``` 请参阅此帖子中的完整示例: [**编组示例 java ArrayList 或 Set**](//howtodoinjava.com/jaxb/jaxb-exmaple-marshalling-and-unmarshalling-list-or-set-of-objects/ "JAXB exmaple: Marshalling and Unmarshalling list or set of objects") **祝您学习愉快!**