java JAXB 需要公共无参数构造函数做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4155361/
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
What JAXB needs a public no-arg constructor for?
提问by yegor256
What does JAXB need a public no-arg constructor for, during marshalling?
在编组期间,JAXB 需要公共无参数构造函数做什么?
Marshaller msh = ctx.createMarshaller();
msh.marshal(object, System.out);
I'm passing an object, not a class. Why does JAXB need a constructor? To construct what?
我正在传递一个对象,而不是一个类。为什么 JAXB 需要构造函数?构建什么?
采纳答案by bdoughan
A JAXB implementation should not need a no-arg constructor during a marshal operation. JAXB does require one for unmarshalling. Normally the absence of a no-arg constructor causes an error when the JAXBContext is created. The JAXB implementation you are using may be delaying initialization until an actual operation is performed.
JAXB 实现在封送操作期间不需要无参数构造函数。JAXB 确实需要一个用于解组。通常,在创建 JAXBContext 时,缺少无参数构造函数会导致错误。您正在使用的 JAXB 实现可能会延迟初始化,直到执行实际操作。
In general support for multi-arg constructors is something we should consider in a future version of JAXB. In the EclipseLink implementation of JAXB (MOXy)we have an enhancement request open for this functionality (feel free to add relevant details):
一般来说,我们应该在 JAXB 的未来版本中考虑对多参数构造函数的支持。在JAXB (MOXy)的EclipseLink 实现中,我们为此功能打开了一个增强请求(随意添加相关细节):
In the current version of JAXB you could use an XmlAdapter to support this use case:
在当前版本的 JAXB 中,您可以使用 XmlAdapter 来支持此用例:
回答by David Moles
As others have noted, it shouldn't really need one but (at least in Sun's implementation) it does. You can get around this with a dummy constructor:
正如其他人所指出的,它不应该真的需要一个,但(至少在 Sun 的实现中)它确实需要。您可以使用虚拟构造函数解决此问题:
private MyObject() {
throw new UnsupportedOperationException("No-arg constructor is just to keep JAXB from complaining");
}
回答by Andrzej Doyle
The same as many frameworks - simplicity and consistency. It allows the library to simple call Class.newInstance()without having to worry about how to specify certain dependencies for a constructor that takes them. JAXB doesn't want to concern itself with full-on Dependency Injection above and beyond the attribute-based setting it already does.
与许多框架相同 - 简单性和一致性。它允许库简单地调用Class.newInstance()而不必担心如何为接受它们的构造函数指定某些依赖项。JAXB 不想在它已经完成的基于属性的设置之外关注完整的依赖注入。
It's a shame in some ways as it means these classes can't be immutable, but that's the trade-off to be made.
在某些方面这是一种耻辱,因为这意味着这些类不能是一成不变的,但这是要进行的权衡。