Java 使用 JAXB 时是否总是需要 ObjectFactory 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2667724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:34:29  来源:igfitidea点击:

Do you always need an ObjectFactory class when using JAXB?

javajaxb

提问by Marcus Leon

Do you always need an ObjectFactory class when using JAXB?

使用 JAXB 时是否总是需要 ObjectFactory 类?

Without it I get this exception:

没有它我得到这个例外:

javax.xml.bind.JAXBException: "com.a.b.c" doesnt contain ObjectFactory.class or jaxb.index

javax.xml.bind.JAXBException: "com.abc" 不包含 ObjectFactory.class 或 jaxb.in​​dex

I gatherthe ObjectFactory can be overkill. But given this exception I'm guessing you need it.. but not sure why?

收集了的ObjectFactory可以矫枉过正。但考虑到这个例外,我猜你需要它......但不知道为什么?

采纳答案by skaffman

You get that exception when you use the JAXBContext.newInstance(String)factory method, where you pass in the package name as the argument. This doesrequire the ObjectFactoryto be there, otherwise, JAXB doesn't know which classes to process.

当您使用JAXBContext.newInstance(String)工厂方法时,您会遇到该异常,在该方法中您将包名称作为参数传递。这确实需要ObjectFactory存在,否则,JAXB 不知道要处理哪些类。

If you don't have an ObjectFactory, you need to JAXBContext.newInstance(Class...)instead, passing in the explicit list of annotated classes to add to the context.

如果您没有ObjectFactory,则需要JAXBContext.newInstance(Class...)改为传入带注释的类的显式列表以添加到上下文中。

回答by bdoughan

Instead of the ObjectFactory you can include a jaxb.index file which is a text file that contains a new line seperated list of Java classes.

您可以包含一个 jaxb.in​​dex 文件,而不是 ObjectFactory,该文件是一个文本文件,其中包含一个新行分隔的 Java 类列表。

For an example of using a jaxb.index file see:

有关使用 jaxb.in​​dex 文件的示例,请参阅:

回答by Anand Rockzz

I was using Springand I just had to change

我正在使用Spring而我只需要改变

Jaxb2Marshaller mlr = new Jaxb2Marshaller();
mlr.setContextPaths("","");

to

Jaxb2Marshaller mlr = new Jaxb2Marshaller();
mlr.setPackagesToScan("","");