0

两篇读后

如何将 Class 作为参数传递并在 Java 中返回泛型集合?

如何在 Java 中将类作为参数传递?

我不确定如何将 JibX 生成的类作为参数传递给序列化对象的方法。

我想完成类似以下的事情。

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;
}

该类仅用于定义 BindingDirectory 用于将对象序列化为的内容。

4

1 回答 1

0

我可能会更好地避免试图通过这门课。我可以通过传递 IBindingFactory 并向调用者添加一些代码来实现相同的效果。

结果最终会是这样。

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;
}
于 2013-06-03T16:23:55.757 回答