Java 怎么新建XML输入工厂(XMLInputFactory)

2019年7月21日19:53:50Java 怎么新建XML输入工厂(XMLInputFactory)已关闭评论 541 1730字阅读5分46秒

1.简介

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

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(newXMLInputFactory());
    }
    static final String CONFIGURED_INPUT_FACTORY = System
            .getProperty("javax.xml.stream.XMLInputFactory");
    static final boolean CHECK_PARENT = Boolean
            .getBoolean("protostuff.loader.check_parent");
    private static final String[] INPUT_FACTORY_IMPLS = new String[] {
            "com.fasterxml.aalto.stax.InputFactoryImpl",
            "com.ctc.wstx.stax.WstxInputFactory",
            "com.sun.xml.fastinfoset.stax.factory.StAXInputFactory",
            "com.sun.xml.internal.stream.XMLInputFactoryImpl" };
    static XMLInputFactory newXMLInputFactory() {
        if (CONFIGURED_INPUT_FACTORY != null) {
            Class<?> c = loadClass(CONFIGURED_INPUT_FACTORY,
                    XmlIOFactoryUtil.class, CHECK_PARENT);
            if (c == null)
                throw new IllegalStateException("Could not load class: "
                        + CONFIGURED_INPUT_FACTORY);

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

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

        throw new IllegalStateException(
                "Cannot find impl for javax.xml.stream.XMLInputFactory");
    }
    
    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;
    }
}

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