ServiceLoader.java revision 2362
2362N/A * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 0N/A * This code is free software; you can redistribute it and/or modify it 0N/A * under the terms of the GNU General Public License version 2 only, as 2362N/A * published by the Free Software Foundation. Oracle designates this 0N/A * particular file as subject to the "Classpath" exception as provided 2362N/A * by Oracle in the LICENSE file that accompanied this code. 0N/A * This code is distributed in the hope that it will be useful, but WITHOUT 0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 0N/A * version 2 for more details (a copy is included in the LICENSE file that 0N/A * accompanied this code). 0N/A * You should have received a copy of the GNU General Public License version 0N/A * 2 along with this work; if not, write to the Free Software Foundation, 0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2362N/A * or visit www.oracle.com if you need additional information or have any 0N/A * A simple service-provider loading facility. 0N/A * <p> A <i>service</i> is a well-known set of interfaces and (usually 0N/A * abstract) classes. A <i>service provider</i> is a specific implementation 0N/A * of a service. The classes in a provider typically implement the interfaces 0N/A * and subclass the classes defined in the service itself. Service providers 0N/A * can be installed in an implementation of the Java platform in the form of 0N/A * extensions, that is, jar files placed into any of the usual extension 0N/A * directories. Providers can also be made available by adding them to the 0N/A * application's class path or by some other platform-specific means. 0N/A * <p> For the purpose of loading, a service is represented by a single type, 0N/A * that is, a single interface or abstract class. (A concrete class can be 0N/A * used, but this is not recommended.) A provider of a given service contains 0N/A * one or more concrete classes that extend this <i>service type</i> with data 0N/A * and code specific to the provider. The <i>provider class</i> is typically 0N/A * not the entire provider itself but rather a proxy which contains enough 0N/A * information to decide whether the provider is able to satisfy a particular 0N/A * request together with code that can create the actual provider on demand. 0N/A * The details of provider classes tend to be highly service-specific; no 0N/A * single class or interface could possibly unify them, so no such type is 0N/A * defined here. The only requirement enforced by this facility is that 0N/A * provider classes must have a zero-argument constructor so that they can be 0N/A * instantiated during loading. 0N/A * <p><a name="format"> A service provider is identified by placing a 0N/A * <i>provider-configuration file</i> in the resource directory 0N/A * The file contains a list of fully-qualified binary names of concrete 0N/A * provider classes, one per line. Space and tab characters surrounding each 0N/A * name, as well as blank lines, are ignored. The comment character is 0N/A * <tt>'#'</tt> (<tt>'\u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on 0N/A * each line all characters following the first comment character are ignored. 0N/A * The file must be encoded in UTF-8. 0N/A * <p> If a particular concrete provider class is named in more than one 0N/A * configuration file, or is named in the same configuration file more than 0N/A * once, then the duplicates are ignored. The configuration file naming a 0N/A * particular provider need not be in the same jar file or other distribution 0N/A * unit as the provider itself. The provider must be accessible from the same 0N/A * class loader that was initially queried to locate the configuration file; 0N/A * note that this is not necessarily the class loader from which the file was 0N/A * <p> Providers are located and instantiated lazily, that is, on demand. A 0N/A * service loader maintains a cache of the providers that have been loaded so 0N/A * far. Each invocation of the {@link #iterator iterator} method returns an 0N/A * iterator that first yields all of the elements of the cache, in 0N/A * instantiation order, and then lazily locates and instantiates any remaining 0N/A * providers, adding each one to the cache in turn. The cache can be cleared 0N/A * via the {@link #reload reload} method. 0N/A * <p> Service loaders always execute in the security context of the caller. 0N/A * Trusted system code should typically invoke the methods in this class, and 0N/A * the methods of the iterators which they return, from within a privileged 0N/A * <p> Instances of this class are not safe for use by multiple concurrent 0N/A * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any 0N/A * method in this class will cause a {@link NullPointerException} to be thrown. 0N/A * <p><span style="font-weight: bold; padding-right: 1em">Example</span> 0N/A * Suppose we have a service type <tt>com.example.CodecSet</tt> which is 0N/A * this case it is an abstract class with two abstract methods: 0N/A * public abstract Encoder getEncoder(String encodingName); 0N/A * public abstract Decoder getDecoder(String encodingName);</pre></blockquote> 0N/A * Each method returns an appropriate object or <tt>null</tt> if the provider 0N/A * does not support the given encoding. Typical providers support more than 0N/A * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the 0N/A * <tt>CodecSet</tt> service then its jar file also contains a file named 0N/A * <p> This file contains the single line: 0N/A * com.example.impl.StandardCodecs # Standard codecs</pre></blockquote> 0N/A * <p> The <tt>CodecSet</tt> class creates and saves a single service instance 0N/A * at initialization: 0N/A * private static ServiceLoader<CodecSet> codecSetLoader 0N/A * = ServiceLoader.load(CodecSet.class);</pre></blockquote> 0N/A * <p> To locate an encoder for a given encoding name it defines a static 0N/A * factory method which iterates through the known and available providers, 0N/A * returning only when it has located a suitable encoder or has run out of 0N/A * public static Encoder getEncoder(String encodingName) { 0N/A * for (CodecSet cp : codecSetLoader) { 0N/A * Encoder enc = cp.getEncoder(encodingName); 0N/A * }</pre></blockquote> 0N/A * <p> A <tt>getDecoder</tt> method is defined similarly. 0N/A * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If 0N/A * the class path of a class loader that is used for provider loading includes 0N/A * remote network URLs then those URLs will be dereferenced in the process of 0N/A * searching for provider-configuration files. 0N/A * <p> This activity is normal, although it may cause puzzling entries to be 0N/A * created in web-server logs. If a web server is not configured correctly, 0N/A * however, then this activity may cause the provider-loading algorithm to fail 0N/A * <p> A web server should return an HTTP 404 (Not Found) response when a 0N/A * requested resource does not exist. Sometimes, however, web servers are 0N/A * erroneously configured to return an HTTP 200 (OK) response along with a 0N/A * helpful HTML error page in such cases. This will cause a {@link 0N/A * ServiceConfigurationError} to be thrown when this class attempts to parse 0N/A * the HTML page as a provider-configuration file. The best solution to this 0N/A * problem is to fix the misconfigured web server to return the correct 0N/A * response code (HTTP 404) along with the HTML error page. 0N/A * The type of the service to be loaded by this loader 0N/A * @author Mark Reinhold 0N/A // The class or interface representing the service being loaded 0N/A // The class loader used to locate, load, and instantiate providers 0N/A // Cached providers, in instantiation order 0N/A // The current lazy-lookup iterator 0N/A * Clear this loader's provider cache so that all providers will be 0N/A * <p> After invoking this method, subsequent invocations of the {@link 0N/A * #iterator() iterator} method will lazily look up and instantiate 0N/A * providers from scratch, just as is done by a newly-created loader. 0N/A * <p> This method is intended for use in situations in which new providers 0N/A * can be installed into a running Java virtual machine. 0N/A // Parse a single line from the given configuration file, adding the name 0N/A // on the line to the names list. 0N/A // Parse the content of the given URL as a provider-configuration file. 0N/A // The service type for which providers are being sought; 0N/A // used to construct error detail strings 0N/A // The URL naming the configuration file to be parsed 0N/A // @return A (possibly empty) iterator that will yield the provider-class 0N/A // names in the given configuration file that are not yet members 0N/A // of the returned set 0N/A // @throws ServiceConfigurationError 0N/A // If an I/O error occurs while reading from the given URL, or 0N/A // if a configuration-file format error is detected 0N/A // Private inner class implementing fully-lazy provider lookup 0N/A "Provider " +
cn +
" not found");
0N/A "Provider " +
cn +
" could not be instantiated: " + x,
0N/A throw new Error();
// This cannot happen 0N/A * Lazily loads the available providers of this loader's service. 0N/A * <p> The iterator returned by this method first yields all of the 0N/A * elements of the provider cache, in instantiation order. It then lazily 0N/A * loads and instantiates any remaining providers, adding each one to the 0N/A * <p> To achieve laziness the actual work of parsing the available 0N/A * provider-configuration files and instantiating providers must be done by 0N/A * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and 0N/A * {@link java.util.Iterator#next next} methods can therefore throw a 0N/A * {@link ServiceConfigurationError} if a provider-configuration file 0N/A * violates the specified format, or if it names a provider class that 0N/A * cannot be found and instantiated, or if the result of instantiating the 0N/A * class is not assignable to the service type, or if any other kind of 0N/A * exception or error is thrown as the next provider is located and 0N/A * instantiated. To write robust code it is only necessary to catch {@link 0N/A * ServiceConfigurationError} when using a service iterator. 0N/A * <p> If such an error is thrown then subsequent invocations of the 0N/A * iterator will make a best effort to locate and instantiate the next 0N/A * available provider, but in general such recovery cannot be guaranteed. 0N/A * <blockquote style="font-size: smaller; line-height: 1.2"><span 0N/A * style="padding-right: 1em; font-weight: bold">Design Note</span> 0N/A * Throwing an error in these cases may seem extreme. The rationale for 0N/A * this behavior is that a malformed provider-configuration file, like a 0N/A * malformed class file, indicates a serious problem with the way the Java 0N/A * virtual machine is configured or is being used. As such it is 0N/A * preferable to throw an error rather than try to recover or, even worse, 0N/A * fail silently.</blockquote> 0N/A * <p> The iterator returned by this method does not support removal. 0N/A * Invoking its {@link java.util.Iterator#remove() remove} method will 0N/A * cause an {@link UnsupportedOperationException} to be thrown. 0N/A * @return An iterator that lazily loads providers for this loader's 0N/A * Creates a new service loader for the given service type and class 0N/A * The interface or abstract class representing the service 0N/A * The class loader to be used to load provider-configuration files 0N/A * and provider classes, or <tt>null</tt> if the system class 0N/A * loader (or, failing that, the bootstrap class loader) is to be 0N/A * @return A new service loader 0N/A * Creates a new service loader for the given service type, using the 0N/A * current thread's {@linkplain java.lang.Thread#getContextClassLoader 0N/A * context class loader}. 0N/A * <p> An invocation of this convenience method of the form 0N/A * ServiceLoader.load(<i>service</i>)</pre></blockquote> 0N/A * ServiceLoader.load(<i>service</i>, 0N/A * Thread.currentThread().getContextClassLoader())</pre></blockquote> 0N/A * The interface or abstract class representing the service 0N/A * @return A new service loader 0N/A * Creates a new service loader for the given service type, using the 0N/A * extension class loader. 0N/A * <p> This convenience method simply locates the extension class loader, 0N/A * call it <tt><i>extClassLoader</i></tt>, and then returns 0N/A * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote> 0N/A * <p> If the extension class loader cannot be found then the system class 0N/A * loader is used; if there is no system class loader then the bootstrap 0N/A * class loader is used. 0N/A * <p> This method is intended for use when only installed providers are 0N/A * desired. The resulting service will only find and load providers that 0N/A * have been installed into the current Java virtual machine; providers on 0N/A * the application's class path will be ignored. 0N/A * The interface or abstract class representing the service 0N/A * @return A new service loader 0N/A * Returns a string describing this service. 0N/A * @return A descriptive string