Java 怎么新建XML输出工厂(XMLOutputFactory)

2019年7月21日19:53:14Java 怎么新建XML输出工厂(XMLOutputFactory)已关闭评论 526 1748字阅读5分49秒

1.简介

Java 怎么新建XML输出工厂(XMLOutputFactory)?——请看下文。

2.示例代码

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

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;

public class Main{
    public static void main(String[] argv) throws Exception{
        System.out.println(newXMLOutputFactory());
    }
    static final String CONFIGURED_OUTPUT_FACTORY = System
            .getProperty("javax.xml.stream.XMLOutputFactory");
    static final boolean CHECK_PARENT = Boolean
            .getBoolean("protostuff.loader.check_parent");
    private static final String[] OUTPUT_FACTORY_IMPLS = new String[] {
            "com.fasterxml.aalto.stax.OutputFactoryImpl",
            "com.ctc.wstx.stax.WstxOutputFactory",
            "com.sun.xml.fastinfoset.stax.factory.StAXOutputFactory",
            "com.sun.xml.internal.stream.XMLOutputFactoryImpl" };
    static XMLOutputFactory newXMLOutputFactory() {
        if (CONFIGURED_OUTPUT_FACTORY != null) {
            Class<?> c = loadClass(CONFIGURED_OUTPUT_FACTORY,
                    XmlIOFactoryUtil.class, CHECK_PARENT);
            if (c == null)
                throw new IllegalStateException("Could not load class: "
                        + CONFIGURED_OUTPUT_FACTORY);

            try {
                return (XMLOutputFactory) c.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        for (String s : OUTPUT_FACTORY_IMPLS) {
            Class<?> c = loadClass(s, XmlIOFactoryUtil.class, CHECK_PARENT);
            if (c != null) {
                try {
                    return (XMLOutputFactory) c.newInstance();
                } catch (Exception e) {
                    
                    
                    continue;
                }
            }
        }

        throw new IllegalStateException(
                "Cannot find impl for javax.xml.stream.XMLOutputFactory");
    }
    
    static Class<?> loadClass(String className, Class<?> context,
            boolean checkParent) {
        Class<?> clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader()
                    .loadClass(className);
        } catch (ClassNotFoundException e) {
            if (context != null) {
                ClassLoader loader = context.getClassLoader();
                while (loader != null) {
                    try {
                        clazz = loader.loadClass(className);
                        return clazz;
                    } catch (ClassNotFoundException e1) {
                        loader = checkParent ? loader.getParent() : null;
                    }
                }
            }
        }
        return clazz;
    }
}

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