How to Use Apache Commons Discovery

1) Create the CommonsSample.java file:

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

import static java.lang.System.out;

public final class CommonsSample {

  public static void main(final String[] args) {

    try {
      final DiscoverClass discoverer = new DiscoverClass();

      final Class cls = discoverer.find(HelloWorldIfc.class);

      final HelloWorldIfc helloWorld = (HelloWorldIfc)cls.newInstance();

      out.println(helloWorld.sayHello());
    }

    catch (final IllegalAccessException e) {
      e.printStackTrace();
    }

    catch (final InstantiationException e) {
      e.printStackTrace();
    }

  }

}

2) Create the HelloWorldIfc.java file:

public interface HelloWorldIfc {
  String sayHello();
}

3) Create the HelloWorldImpl.java file:

public final class HelloWorldImpl implements HelloWorldIfc {

  public String sayHello() {
    return "Hello World!";
  }

}

4) Compile the CommonsSample.java, HelloWorldIfc.java and HelloWorldImpl.java files.

5) Set the HelloWorldIfc system property to HelloWorldImpl.

6) Launch the CommonsSample class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s