Java XML JAXB Marshaller marshal(Object obj, Class clazz)

Here you can find the source of marshal(Object obj, Class clazz)

Description

marshal

License

Open Source License

Declaration

public static String marshal(Object obj, Class<?> clazz) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    private static ConcurrentHashMap<String, JAXBContext> contextMap = new ConcurrentHashMap<String, JAXBContext>();

    public static String marshal(Object obj, Class<?> clazz) {
        String result = null;/*  ww  w.  j a  v  a2  s  . com*/

        try {
            JAXBContext context = contextMap.get(clazz.getPackage().getName());
            if (context == null) {
                context = JAXBContext.newInstance(clazz.getPackage().getName());
                contextMap.put(clazz.getPackage().getName(), context);
            }

            Marshaller m = context.createMarshaller();

            StringWriter writer = new StringWriter();

            m.marshal(obj, writer);

            result = writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException("Can't marshal the XML file, error message: " + e.getMessage());
        }

        return result;
    }
}

Related

  1. marshal(Object bean)
  2. marshal(Object entity)
  3. marshal(Object obj)
  4. marshal(Object obj)
  5. marshal(Object obj)
  6. marshal(Object obj, OutputStream out)
  7. marshal(Object obj, OutputStream out, Class... boundClasses)
  8. marshal(Object obj, OutputStream stream)
  9. marshal(Object object)