static T load()

in dom/src/main/java/org/apache/james/mime4j/dom/ServiceLoader.java [41:88]


    static <T> T load(Class<T> spiClass) {
        String spiResURI = "META-INF/services/" + spiClass.getName();
        ClassLoader classLoader = spiClass.getClassLoader();
        try {
             Enumeration<URL> resources = classLoader.getResources(spiResURI);
             while (resources.hasMoreElements()) {
                 URL resource = resources.nextElement();
                 InputStream instream = resource.openStream();
                 try {
                     BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                     String line;
                     while ((line = reader.readLine()) != null) {
                        line = line.trim();
                         int cmtIdx = line.indexOf('#');
                         if (cmtIdx != -1) {
                             line = line.substring(0, cmtIdx);
                             line = line.trim();
                         }

                         if (line.length() == 0) {
                             continue;
                         }

                         Class<?> implClass = classLoader.loadClass(line);
                        if (spiClass.isAssignableFrom(implClass)) {
                            Object impl = implClass.newInstance();
                            return spiClass.cast(impl);
                        }
                    }
                     reader.close();
                 } finally {
                     instream.close();
                }
            }
             return null;
         } catch (IOException ex) {
             throw new ServiceLoaderException(ex);
         } catch (ClassNotFoundException ex) {
             throw new ServiceLoaderException("Unknown SPI class '"
                     + spiClass.getName() + "'", ex);
         } catch (IllegalAccessException ex) {
             // Not visible
             return null;
         } catch (InstantiationException ex) {
             throw new ServiceLoaderException("SPI class '"
                     + spiClass.getName() + "' cannot be instantiated", ex);
        }
    }