Search code examples
javainterface

Find Java classes implementing an interface


Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?

Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.


Solution

  • A while ago, I put together a package for doing what you want and more. (I needed it for a utility I was writing). It uses the ASM library. You can use reflection, but ASM turned out to perform better.

    I put my package in an open-source library I have on my website. The library is here: http://software.clapper.org/javautil/. You want to start with the ClassFinder class.

    The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple of directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.

    The library is BSD-licensed, so you can safely bundle it with your code. The source is available.

    If that's useful to you, help yourself.

    Update: If you're using Scala, you might find this library to be more Scala-friendly.