'If I want to access a particular interface, how do I know which class to instantiate ?'
There are several ways in which this can be accomplished. One common method is to provide a configuration file, such as a property file, but then you have to look for the property file in a well known location. You could also do a brute force search over classes on the classpath to see which ones implement the required interface. The trouble is that this can not only be very slow, but also fails to deal with the situation where the interface is implemented by multiple classes. Looking to solve this problem I came across the javax.imageio.spi.ServiceRegistry class which has been part of Java since 1.42. Full documentation is available in the JavaDocs but the general idea is that you add an entry under the META-INF directory which names an interface and the corresponding class which should be instantiated.
For example, in the Apache Kato API we have an interface called ImageFactory which is the entry point for analysing a core file. However what you don't know is the name of the class to instantiate which implements this interface, so using the mechanism provided by the ServiceRegistry class we do the following
- Create a file under the META-INF/services directory called org.kato.api.image.ImageFactory.
- The file org.kato.api.image.ImageFactory contains a single line which is the name of the class to instantiate.
Then when an application starts, it can find out from the ServiceRegistry class at run time which class should be used.
A nice simple mechanism which comes for free, and something which I intend to make use of in some of the Eclipse plugin's I'm currently writing.
The postings on this site are my own and don't necessarily represent IBM's positions, strategies or opinions.