Here you can find the source of marshal(Object entity)
Marshal an object into a byte array.
Parameter | Description |
---|---|
entity | object to marshal |
Parameter | Description |
---|---|
RuntimeException | If any unexpected errors occur while marshalling |
public static byte[] marshal(Object entity)
//package com.java2s; //License from project: Open Source License import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import javax.xml.bind.*; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Map; public class Main { private static final Map<Class<?>, JAXBContext> CONTEXTS = Maps.newHashMap(); /**//from w w w . j a v a 2 s. c o m * <p>Marshal an object into a byte array. Output is formatted and has "UTF-8" encoding.</p> * * @param entity object to marshal * @return byte array of marshaled entity * @throws RuntimeException If any unexpected errors occur while marshalling */ public static byte[] marshal(Object entity) { return marshal(entity, ImmutableMap.<String, Object>of(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE, Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.toString())); } /** * <p>Marshal an object into a byte array with specified marshaller options.</p> * * @param entity object to marshal * @param options marshaller options * @return byte array of marshaled entity * @throws RuntimeException If any unexpected errors occur while marshalling */ public static byte[] marshal(Object entity, Map<String, Object> options) { try { Class<?> entityClass = (entity instanceof JAXBElement) ? ((JAXBElement) entity).getDeclaredType() : entity.getClass(); Marshaller marshaller = getContext(entityClass).createMarshaller(); for (Map.Entry<String, Object> option : options.entrySet()) { marshaller.setProperty(option.getKey(), option.getValue()); } ByteArrayOutputStream os = new ByteArrayOutputStream(); marshaller.marshal(entity, os); return os.toByteArray(); } catch (JAXBException e) { throw new RuntimeException("Failed to marshall object", e); } } private static JAXBContext getContext(Class<?> clazz) { JAXBContext context = CONTEXTS.get(clazz); if (context == null) { try { context = JAXBContext.newInstance(clazz); } catch (JAXBException e) { throw new RuntimeException("Failed to create JAXBContext for type " + clazz, e); } CONTEXTS.put(clazz, context); } return context; } }