Priyank Doshi
Priyank Doshi

Reputation: 13151

Convert non-generic method to generic method

I have following method:

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() method takes different types of arguments. See here It takes:

  1. ContentHandler
  2. OutputStream
  3. XmlEventWriter
  4. XMLStreamWriter etc.

How to modify the above method such that instead of System.out , I can pass the destination of marshalling in function argument.

For e.g. I want to call method like:

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

Likewise.

I tried following with fun(obj1,PrintStream.class,System.out) but it was unsuccessfull:

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

Upvotes: 0

Views: 164

Answers (1)

nd.
nd.

Reputation: 8932

You don't need to add additional generic parameters to your method. Simply pass a javax.xml.transform.Result to the marshaller:

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

You can use the StreamResult for writing to System.out or to a file:

fun(foo, new StreamResult(System.out));
fun(foo, new StreamResult(file_pointer.openOutputStream()));

Upvotes: 3

Related Questions