查找实现接口的 Java 类
前段时间,我遇到了一段代码,它使用一些标准的 Java 功能来定位实现给定接口的类.我知道这些函数隐藏在一些非逻辑的地方,但它们可以用于其他类,正如包名所暗示的那样.当时我不需要它,所以我忘记了,但现在我需要,而且我似乎再也找不到这些功能了.在哪里可以找到这些功能?
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?
我不是在寻找任何 IDE 功能或任何东西,而是寻找可以在 Java 应用程序中执行的东西.
I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.
不久前,我整理了一个包来做你想做的事,等等.(我正在编写的实用程序需要它).它使用 ASM 库.您可以使用反射,但结果证明 ASM 的性能更好.
Awhile 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.
我将我的包放在我网站上的一个开源库中.该库位于:http://software.clapper.org/javautil/.您想从 ClassFinder 类开始.
I put my package in an open source library I have on my web site. The library is here: http://software.clapper.org/javautil/. You want to start with the with ClassFinder class.
我为它编写的实用程序是一个 RSS 阅读器,我仍然每天都在使用它,因此代码确实会得到锻炼.我使用 ClassFinder 来支持 RSS 阅读器中的插件 API;在启动时,它会在几个目录树中查找包含实现某个接口的类的 jar 和类文件.它比您预期的要快得多.
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 directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.
该库是 BSD 许可的,因此您可以安全地将其与您的代码捆绑在一起.来源可用.
The library is BSD-licensed, so you can safely bundle it with your code. Source is available.
如果这对您有用,请帮助您自己.
If that's useful to you, help yourself.
更新:如果您使用 Scala,您可能会发现这个库更像 Scala-友好.
Update: If you're using Scala, you might find this library to be more Scala-friendly.