[英]Passing a Class for object serialization to xml
After reading both 看完之后
How can I pass a Class as parameter and return a generic collection in Java? 如何在Java中传递Class作为参数并返回通用集合?
and 和
How do I pass a class as a parameter in Java? 如何在Java中将类作为参数传递?
I am unsure how I would pass a JibX generated class as a parameter to a method that serializes the object. 我不确定如何将JibX生成的类作为参数传递给序列化对象的方法。
I would like to accomplish something like the following. 我想完成类似以下的事情。
protected static String SerializeObject( Class clazz , Object request)
{
String message = null;
try
{
IBindingFactory lBindingFactory = BindingDirectory.getFactory(
clazz.class);
IMarshallingContext lContext = lBindingFactory.
createMarshallingContext();
ByteArrayOutputStream lOutputStream = new ByteArrayOutputStream();
lContext.marshalDocument(request, "UTF-8", null,
lOutputStream);
message = new String(lOutputStream.toByteArray(), "UTF-8");
}
catch (JiBXException lEx)
{
throw new RuntimeException("Problems generating XML, " +
"underlying problem is " + lEx.getMessage(), lEx);
}
catch (UnsupportedEncodingException lEx)
{
throw new RuntimeException("Problems generating XML in specified" +
"encoding, underlying problem is " + lEx.getMessage(), lEx);
}
return message;
}
Where the class is only used to define what the BindingDirectory is using to serialize the object into. 该类仅用于定义BindingDirectory用于将对象序列化到的内容。
I might be better to avoid attempting to pass the class at all. 我最好还是避免尝试通过所有课程。 I can achieve the same affect by passing the IBindingFactory and adding a bit of code to the caller. 我可以通过传递IBindingFactory并向调用方添加一些代码来达到相同的效果。
The result would end up like this. 结果将像这样结束。
protected static String SerializeObject( IBindingFactory lBindingFactory,
Object request)
{
String message = null;
try
{
IMarshallingContext lContext = lBindingFactory.
createMarshallingContext();
ByteArrayOutputStream lOutputStream = new ByteArrayOutputStream();
lContext.marshalDocument(request, "UTF-8", null,
lOutputStream);
message = new String(lOutputStream.toByteArray(), "UTF-8");
}
catch (JiBXException lEx)
{
throw new RuntimeException("Problems generating XML, " +
"underlying problem is " + lEx.getMessage(), lEx);
}
catch (UnsupportedEncodingException lEx)
{
throw new RuntimeException("Problems generating XML in specified" +
"encoding, underlying problem is " + lEx.getMessage(), lEx);
}
return message;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.