Java 怎么使用JAXB marshall助手

2019年7月21日19:57:08Java 怎么使用JAXB marshall助手已关闭评论 583 1409字阅读4分41秒

1.简介

Java 怎么使用JAXB marshall助手?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import java.io.OutputStream;

import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import javax.xml.transform.Result;
import org.w3c.dom.Node;

public class Main {
    public static void marshall(Object object, Node root,
            Marshaller.Listener listener) throws JAXBException {
        Marshaller marshaller = createMarshaller(object.getClass(),
                listener);
        marshaller.marshal(object, root);
    }

    public static void marshall(Object object, OutputStream os,
            Marshaller.Listener listener) throws JAXBException {
        Marshaller marshaller = createMarshaller(object.getClass(),
                listener);
        marshaller.marshal(object, os);
    }

    public static void marshall(Object object, Result result,
            Marshaller.Listener listener) throws JAXBException {
        Marshaller marshaller = createMarshaller(object.getClass(),
                listener);
        marshaller.marshal(object, result);
    }

    public static void marshall(Object object, Writer writer,
            Marshaller.Listener listener) throws JAXBException {
        Marshaller marshaller = createMarshaller(object.getClass(),
                listener);
        marshaller.marshal(object, writer);
    }

    private static <T> Marshaller createMarshaller(Class<T> clazz,
            Marshaller.Listener listener) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Marshaller marshaller = jc.createMarshaller();
        if (listener != null) {
            marshaller.setListener(listener);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        return marshaller;
    }
}

 
继续阅读
编程十万个怎么办