Thursday, May 3, 2012

Retrieve the classes implementing a particular interface programmatically in Java

I recently had a requirement to retrieve all the classes that implement a particular service interface programmatically in Java. While searching for some way to get my requirement fulfilled I came across the class ServceLoader exposed by java.util.* package as a part of Java 1.6 APIs. 

Shown below is a sample scenario where you can use the aforementioned class effectively to retrieve the service providers (typically implementer classes of an interface or an abstract class) list that implement a particular service (typically a well known interface or abstract classs).

Assume I want to register the set of implementer classes of the java.sql.Driver interface that exists in my current thread's classloader explicitely. You can accomplish that task in the following manner.

NOTE:
If a particular service provider implements a service interface then the jar containing those implementer classes carries the provider-configuration file in the resource directory similar to the following format.

Eg: META-INF/services/java.sql.Driver
ClassLoader callerCL = Thread.currentThread().getContextClassLoader();
ServiceLoader<Driver> servLoader = ServiceLoader.load(java.sql.Driver.class, callerCL);
for (Driver driver : servLoader) {
   String driverName = driver.getClass().getName();
   try {
       Class.forName(driverName);
   } catch (ClassNotFoundException e) {
       log.error("Unable to registery driver class '" + driverName + "'", e);
   }
}

No comments:

Post a Comment