(五)泛型-泛型应用之XML和实体类型的转化

使用泛型写工具类可以极大的提高代码的重复利用率,写代码的感觉都不一样了呢。泛型的应用都是干货满满的。本文将使用泛型实现 xml 字符串和 Java Bean 的相互转化。

本文的重点是下面这个具备泛型方法的类

一个可以指定编码格式、完成 xml 与 Java Bean互转的泛型方法工具类

package com.bestcxx.stu.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

/**
 * @Title: 工具类
 * @Description: xml类型和实体类型转化的工具类
 * @Version: v1.0
 */
public class XmlBeanUtil {

    /**
     * 将 String 类型转化为指定实体
     *
     * @param xml 待转化的字符串
     * @param c
     *            实体类的类型
     * @param encoding
     *            字符类型 UTF8、GBK
     * @return
     * @throws JAXBException
     * @throws UnsupportedEncodingException
     */
    public static <E> E  XmlToBeanEncoding(String xml, Class<?> c, String encoding) throws JAXBException, UnsupportedEncodingException {
        JAXBContext context = JAXBContext.newInstance(c);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        @SuppressWarnings("unchecked")
        E e = (E) unmarshaller.unmarshal(new ByteArrayInputStream(xml.getBytes(encoding)));

        return e;
    }


    /**
     * 指定 GBK 是ok的
     *
     * @param obj
     *            实体类
     * @param encoding
     *            字符类型,比如 UTF8、GBK
     * @return
     * @throws JAXBException
     */
    public static <T> String BeanToXmlEncoding(T obj, String encoding) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = jc.createMarshaller();
        // 乱码转换
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        // 格式化生成的xml串
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        // 是否省略XML头申明信息
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        marshaller.marshal(obj, result);
        // 转码
        byte[] bystr = out.toByteArray();
        String str = "";
        try {
            str = new String(bystr, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

}
上面的方法怎么使用呢?

我将在另外一篇文章中进行介绍,因为涉及到其他部分的知识,放在这的话显得泛型好像很麻烦的样子。
运用泛型实现复杂对象与 XML 的互转

猜你喜欢

转载自blog.csdn.net/bestcxx/article/details/80574294