Java 怎么使用JAXB Unmarshaller助手

2019年7月21日19:56:25Java 怎么使用JAXB Unmarshaller助手已关闭评论 838 1577字阅读5分15秒

1.简介

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

2.示例代码

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


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.Reader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

import org.w3c.dom.Node;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, Node node,
            Unmarshaller.Listener listener) throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(node);
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, Reader reader,
            Unmarshaller.Listener listener) throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(reader);
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, InputStream inputStream,
            Unmarshaller.Listener listener) throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(inputStream);
    }

    public static <T> T unmarshall(Class<T> clazz, String filename,
            Unmarshaller.Listener listener) throws JAXBException,
            IOException {
        FileInputStream is = null;
        T object;
        try {
            is = new FileInputStream(filename);
            object = unmarshall(clazz, is, listener);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return object;
    }

    private static <T> Unmarshaller getUnmarshaller(Class<T> clazz,
            Unmarshaller.Listener listener) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (listener != null) {
            unmarshaller.setListener(listener);
        }
        return unmarshaller;
    }
}

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