Search for a class in classpath

I'd like to be able to search for classes in my classpath that implement a certain interface.  Anyone know how/if this is possible?

Who is Participating?
doronbConnect With a Mentor Commented:
objects gave you the right way to go about doing this.  All I have to add to this is that looking through the classpath entries and locating *.class files is the easier part because there are actaully two ways to check if any given class implements any given interface.  The first and programatically easiest is to load the class and check if the class implements the interface.  The 2nd way (which you'd be forced to use IF, and only if you really don't want to load the class) is to actually read the constant-pool of the class (meaning load classbyes into memory, a byte[] array would do nicely for that) and check for yourself if the interface is referenced by the classbytes.

Code can be written for both approaches, but you'd have to tackle the class-discovery mechanism first anyway so to start you off on that here's some code:

  // Get the Java-Class-Path..
  String paths = System.getProperty("java.class.path");
  // Seperate paths..
  StringTokenizer st = new StringTokenizer(paths, File.pathSeparator);
  // Go through all entries..
  while (st.hasMoreElements()) {
    // Get the next classpath entry as a String..
    String ss = (String)st.nextElement();
    try {
      // Convert classpath entry to a file..
      File classPathEntry = new File(ss);

Now you have to check if the classpath entry is a director, or a JAR/ZIP file.  If its a directory, you have to look for all the *.class files in that directory, if it is a JAR/ZIP file, you have to load that file into memory using the JAR/ZIP api's and check each class inside it.

Good luck and I hope I've helped to clear things a bit.
objectsConnect With a Mentor Commented:
not easily, you'd need to go thru each entry in path and if a directory go thru all the class files in the directory, load them, and check if they implement inteface.
Similiarily for any jars in classpath, you'd need to open jar and check every file in jar.
can u explain bit more???
Never miss a deadline with

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

dtrustyAuthor Commented:
Well, I basically want to load a drop down full of classes that a user can use.  All of the classes need to implement a certain interface.  If the only way is to go through each entry in path, is there a way to get a list of all of the classes in a classpath?  Thanks  again
there is no easy way.
Thanks :)
All Courses

From novice to tech pro — start learning today.