简体   繁体   English

Java软件包扫描器-查找具有给定接口的所有类

[英]Java package scanner - find all classes with a given interface

In C# you can easily read all classes from a given assembly. 在C#中,您可以轻松地从给定程序集中读取所有类。

I'm looking for equivalent feature in Java. 我正在寻找Java中的等效功能。 I need this to automatically bind EJB beans to my Guice Module. 我需要它来自动将EJB bean绑定到我的Guice模块。

Unfortunately there seems to be no ready-to-use solution in Java. 不幸的是,Java中似乎没有现成的解决方案。

In our project we used a slightly modified approach suggested by some blog . 在我们的项目中,我们使用了一些博客建议的略微修改的方法。 The solution described there is to scan file system and JARs for classes. 此处描述的解决方案是扫描文件系统和JAR中的类。

If you want to pick only classes implementing some interface, you can do some additional check like clazz.isAssignableFrom(MyInterface.class) . 如果只想选择实现某些接口的类,则可以执行一些其他检查,例如clazz.isAssignableFrom(MyInterface.class)

The Java equivalent of an assembly is a JAR file; 程序集的Java等效项是JAR文件。 the contents of a JAR file can be listed by using the classes in java.util.jar . 可以使用java.util.jar的类列出JAR文件的内容。

There is no more general mechnism (like getting all classes in a package) because the Java class loading mechnism is very flexible and allows for things like classes loaded via HTTP or generated on the fly, so it's impossible to know all classes that are available. 由于Java类的加载机制非常灵活,并且允许通过HTTP加载的类或动态生成的类之类的东西,因此不再需要一般的机制(例如将所有类都放入一个软件包中),因此不可能知道所有可用的类。

Here is one, http://grepcode.com/file/repo1.maven.org/maven2/com.metapossum/metapossum-scanner/1.0.1/com/metapossum/utils/scanner/PackageScanner.java 这是一个http://grepcode.com/file/repo1.maven.org/maven2/com.metapossum/metapossum-scanner/1.0.1/com/metapossum/utils/scanner/PackageScanner.java

We used it in our Lightweight Java Framework, Snow, and it works great. 我们在轻量级Java框架Snow中使用了它,并且效果很好。

The maven is like 专家就像

<dependency>
   <groupId>com.metapossum</groupId>
   <artifactId>metapossum-scanner</artifactId>
   <version>1.0.1</version>
</dependency>    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM