In C# you can easily read all classes from a given assembly.
I'm looking for equivalent feat开发者_如何学Pythonure 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>
精彩评论