0

私は次の方法を持っています:

private <U> void fun(U u) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(u.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(u, System.out);
    }

marshal()メソッドは、さまざまなタイプの引数を取ります。ここを参照してください 。

  1. ContentHandler
  2. OutputStream
  3. XmlEventWriter
  4. XMLStreamWriterなど。

System.outの代わりに、関数の引数でマーシャリングの宛先を渡すことができるように、上記のメソッドを変更する方法。

たとえば、次のようなメソッドを呼び出します。

objToXml(obj1,System.out);
outToXml(obj1,file_pointer);

同じく。

でフォローしようとしましfun(obj1,PrintStream.class,System.out)たが、失敗しました:

private <T, U, V> void fun(T t, Class<U> u, V v) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(t.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(t, (U) v);
    }
4

1 に答える 1

3

メソッドにジェネリックパラメーターを追加する必要はありません。javax.xml.transform.Resultをマーシャラーに渡すだけです。

private <U> void fun(U u, Result result) {
  JAXBContext context = JAXBContext.newInstance(u.getClass());
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.marshal(u, result);
}

StreamResultを使用して、System.outまたはファイルに書き込むことができます。

fun(foo, new StreamResult(System.out));
fun(foo, new StreamResult(file_pointer.openOutputStream()));
于 2012-08-09T09:51:44.840 に答える