Re: Service Provider mechanism and javax.imageio.spi.ServiceRegistry
Attila Szegedi <[email protected]>
| Newsgroups | gmane.comp.windows.devel.java.advanced |
|---|---|
| Message-ID | <[email protected]> |
It's easy to dicover and process these files with a bit of custom code. I
have it in few places, most notably here:
<http://dynalang.svn.sourceforge.net/viewvc/dynalang/trunk/dynalang/src/org/dynalang/mop/impl/AutoDiscovery.java?view=markup>
Something like this'll return you a list of service instances for all
declared services within a ClassLoader's scope:
<T> static List<T> getServices(Class<T> serviceItf, ClassLoader cl)
throws IOException, InstantiationException, IllegalAccessException,
ClassNotFoundException {
List<T> list = new LinkedList<T>();
String path = "/META-INF/services/" + serviceItf.getClass().getName();
Enumeration<URL> urls;
if(cl == null) {
urls = ClassLoader.getSystemResources(path);
}
else {
urls = cl.getResources(path);
}
for(;urls.hasMoreElements();) {
URL url = urls.nextElement();
InputStream in = url.openStream();
try {
Properties props = new Properties();
props.load(in);
for (Object className : props.keySet()) {
T serviceInstance = (T)Class.forName(
className.toString(), true, cl).newInstance());
list.add(serviceInstance);
}
finally {
in.close();
}
}
return list;
}
I'm using Properties object 'cause I get skipping of empty lines and
handling of # comments for free. It does not guarantee you that you'll
instantiate the objects in the order they were declared in individual
files though, but I can live with that...
That's it :-)
BTW, it stinks that java.util.Properties doesn't extend Hashtable<String,
String>...
Attila.
On Wed, 31 Oct 2007 15:03:49 +0100, Bertrand Delacretaz
<[email protected]> wrote:
> On 10/31/07, Bertrand Delacretaz <[email protected]> wrote:
>
>> ...But it feels a bit weird to have this in javax.imageio.spi, is there
>> a
>> better alternative?...
>
> Someone mentioned off-list the java.util.ServiceLoader class, which
> looks like what I'm looking for, but it's available starting with Java
> 1.6 only.
>
> -Bertrand
>
--
home: http://www.szegedi.org
weblog: http://constc.blogspot.com
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com