Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import java.io.ByteArrayOutputStream;

public class Main {
    /**
     * Convert a bean to XML format using JAXB.
     * 
     * @param bean
     *            The bean to marshal as XML.
     * @param bc
     *            Additional classes to register on the JAXB context for
     *            marshalling.
     * @return An XML representation of the bean.
     */
    public static <T> String marshal(T bean, Class<?>... bc) {
        assert bean != null;
        Class<?>[] bind;
        if (bc.length > 0) {
            bind = new Class<?>[bc.length + 1];
            bind[0] = bean.getClass();
            for (int i = 0; i < bc.length; i++)
                bind[i + 1] = bc[i];
        } else
            bind = new Class<?>[] { bean.getClass(), };
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(bind);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
            marshaller.marshal(bean, baos);
        } catch (JAXBException e) {
            throw new IllegalStateException("Error marshalling", e);
        }
        return new String(baos.toByteArray());
    }
}