RSS Feed for This PostCurrent Article

Java: Simplified Plugin Finder using Commons Discovery

I have written some articles on developing a simple Java Plugin Framework some times back. In the articles I showed you how to add additional features to existing application framework by implementing a common interface.

To implement a plugin framework, we need to discover all the pluggable interfaces. Since then I have tried Apache Commons Discovery which is perfectly meant for that.

As quoted from the website, the Discovery component is about discovering, or finding, implementations for pluggable interfaces. It provides facilities for instantiating classes in general, and for lifecycle management of singleton (factory) classes. Fundamentally, Discovery locates classes that implement a given Java interface.

Here is a much simplified example.

Let’s say I have a common interface called TestInterface.

public interface TestInterface {
    void write();
}

I have 2 classes, TestImpl_1 and TestImpl_2 that implements the interface.

public class TestImpl_1 implements TestInterface {

    public void write() {
        System.out.println("Test implementation 1");
    }
}



public class TestImpl_2 implements TestInterface{

    public void write() {
        System.out.println("Test implementation 2");
    }
}

To test it,

import org.apache.commons.discovery.tools.DiscoverSingleton;

public class TestCommonsDiscovery {

    public static void main(String[] args) {
        TestInterface obj = (TestInterface)
                     DiscoverSingleton.find(
                                TestInterface.class,
                                "TestImpl_1");
        obj.write();

        DiscoverSingleton.release();
        
        obj = (TestInterface) 
                DiscoverSingleton.find(
                                 TestInterface.class,
                                 "TestImpl_2");
        obj.write();


    }
}

I created DiscoverSingleton class and use to to find the classes that implement the TestInterface.

I need to call the release method so that DiscoverSingleton will release the cache.

The results

Test implementation 1
Test implementation 2


Trackback URL


Sorry, comments for this entry are closed at this time.