All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.lkk.web.util.XmlUtil Maven / Gradle / Ivy

The newest version!
package cn.lkk.web.util;

import java.io.File;
import java.io.InputStream;

import com.thoughtworks.xstream.XStream;

import cn.hutool.core.io.FileUtil;

/**
 * @author wangfujun
 * @date 2018/12/18
 */
public class XmlUtil {

    // 创建 instance 的一个对象
    private static XmlUtil instance = new XmlUtil();

    private XmlUtil() {}

    // 获取唯一可用的对象
    public static XmlUtil getInstance() {
        return instance;
    }

    @SuppressWarnings("unchecked")
    public static  T toBean(Class clazz, InputStream xml) {
        XStream xstream = instance.getStream();
        xstream.processAnnotations(clazz);
        xstream.setClassLoader(clazz.getClassLoader());
        return (T)xstream.fromXML(xml);
    }

    @SuppressWarnings("unchecked")
    public static  T toBean(Class clazz, String xml) {
        XStream xstream = instance.getStream();
        xstream.processAnnotations(clazz);
        xstream.setClassLoader(clazz.getClassLoader());
        return (T)xstream.fromXML(xml);
    }

    public static String toXml(Object obj) {
        XStream xstream = instance.getStream();
        xstream.processAnnotations(obj.getClass());
        xstream.setClassLoader(obj.getClass().getClassLoader());
        return xstream.toXML(obj);
    }

    private XStream getStream() {
        return new XStream();
    }

    public static File getFormFile(String fileName) {
        return FileUtil.file(FileUtil.file(".").getParentFile(), fileName);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy