实现JAXBContext Resolver类:列表中存储了哪些类?

时间:2016-06-14 17:03:00

标签: java jaxb

我正在尝试实现一个JAXBContext解析器类。我不明白的是cTypes中包含哪些类型的类?我已经看过几个类似的例子,但没有一个解释cTypes列表是什么。

@Provider
public class JaxbContextResolver implements ContextResolver<JAXBContext> {

    private final JAXBContext context;
    private final Set<Class<?>> types;
    private final Class<?>[] cTypes = {Flights.class, FlightType.class, AircraftType.class};

    public JaxbContextResolver() throws Exception {
        this.types = new HashSet<Class<?>>(Arrays.asList(cTypes));
        this.context = new JettisonJaxbContext(JettisonConfig.DEFAULT, cTypes);
    }

    @Override
    public JAXBContext getContext(Class<?> objectType) {
        return (types.contains(objectType)) ? context : null;
    }
}

1 个答案:

答案 0 :(得分:1)

您的cTypes类列表必须包含表示根xml元素的所有类(使用@XmlRootElement注释的那些)。

说明:

创建JAXBContext时,为其提供要绑定的类列表:

this.context = new JettisonJaxbContext(JettisonConfig.DEFAULT, cTypes);

这将使JAXB能够将元素与类实际关联。 JAXB将自动绑定根元素类中包含的任何类(除了带注释的@XmlTransient)。

然后,当使用getContext方法时,只有当参数类已被JAXB绑定到所述上下文时,它才会返回类中的初始化上下文,因为您的JAXBContext将无法使用任何类。没约束。