打印 JAXB 生成的 bean
我有一个从 wsimport
生成的 JAXB 数据类,我想将其打印到控制台和/或日志。不幸的是,没有生成 toString。
打印数据对象的最简单方法是什么?输出是原始 XML 还是其他内容并不重要,只要它可读即可。
看起来该类是一个有效的 bean(正确命名的 getter 和 setter),因此任何与 bean 一起使用的东西都可能没问题。
I have a JAXB data class which is generated from wsimport
and I'd like to print it to the console and/or log. Unfortunately a toString is not generated.
What's the easiest way to print the data object? It doesn't matter whether the output is the original XML or something else, as long as it's readable.
It looks like the class is a valid bean (properly named getters and setters) so anything that works with beans is probably fine too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要打印到控制台,请尝试以下操作:
要将其转换为
String
,请使用StringWriter
:对象,您需要执行以下操作:
要获取JAXBContext是
jaxbObject
所属类型的类文字。您还应该能够执行以下操作:取决于您定义上下文的位置和您的风格偏好。
JAXBContext
是线程安全的,因此最好定义一个实例并共享它。但Marshaller
和Unmarshaller
没有做出这样的保证。因此它们需要按需创建。For printing to the console, try this:
To get it into a
String
, use aStringWriter
:To get the JAXBContext object you need to do the following:
Where
<WhateverClass>
is the class literal for the type thatjaxbObject
is. You should also be able to do:Depending on where you are defining the context and your stylistic preference.
JAXBContext
is thread-safe so it is good to define one instance and share it.Marshaller
andUnmarshaller
make no such guarantees though. So they need to be created on demand.