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:
- ContentHandler
- OutputStream
- XmlEventWriter
- 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);
}
You don’t need to add additional generic parameters to your method. Simply pass a javax.xml.transform.Result to the marshaller:
You can use the StreamResult for writing to System.out or to a file: