简体   繁体   中英

Java package scanner - find all classes with a given interface

In C# you can easily read all classes from a given assembly.

I'm looking for equivalent feature in Java. I need this to automatically bind EJB beans to my Guice Module.

Unfortunately there seems to be no ready-to-use solution in 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.

If you want to pick only classes implementing some interface, you can do some additional check like clazz.isAssignableFrom(MyInterface.class) .

The Java equivalent of an assembly is a JAR file; the contents of a JAR file can be listed by using the classes in java.util.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.

Here is one, 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.

The maven is like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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