Skip to content

Instantly share code, notes, and snippets.

@antoniocaccamo
Last active May 6, 2021 14:56
Show Gist options
  • Save antoniocaccamo/c42ed4257f18d66fda7ff39365748f80 to your computer and use it in GitHub Desktop.
Save antoniocaccamo/c42ed4257f18d66fda7ff39365748f80 to your computer and use it in GitHub Desktop.
dynamic jaxb marshalling
public static <T> void marshal (Writer writer, Class<T> aclass, T tobj) {
try {
Object toMarshall = tobj;
JAXBContext context = JAXBContext.newInstance(tobj.getClass().getPackage().getName());
// è un XmlRootElement
if ( tobj.getClass().getAnnotation(XmlRootElement.class) == null ) {
JAXBElement<T> ttobj = new JAXBElement(
new QName("", tobj.getClass().getSimpleName().toLowerCase()),
aclass,
tobj
);
toMarshall = ttobj;
}
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(toMarshall, writer);
} catch (JAXBException e) {
LOGGER.error("error", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment