I need to read classes contained in a Java package. Those classes are in classpath. I need to do this task from a Java program directly. Do you know a simple way to do?
List<Class> classes = readClassesFrom("my.package")
I need to read classes contained in a Java package. Those classes are in classpath. I need to do this task from a Java program directly. Do you know a simple way to do?
List<Class> classes = readClassesFrom("my.package")
Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.
Hibernate has this already written:
CDI might solve this, but don't know - haven't investigated fully yet
.
Also for annotations:
The most robust mechanism for listing all classes in a given package is currently ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author.)
You could use the Reflections Project described here
It's quite complete and easy to use.
Brief description from the above website:
Example:
That functionality is still suspiciously missing from the Java reflection API as far as I know. You can get a package object by just doing this:
But as you probably noticed, that won't let you list the classes in that package. As of right now, you have to take sort of a more filesystem-oriented approach.
I found some sample implementations in this post
I'm not 100% sure these methods will work when your classes are buried in JAR files, but I hope one of those does it for you.
I agree with @skaffman...if you have another way of going about this, I'd recommend doing that instead.
If you have Spring in you classpath then the following will do it.
Find all classes in a package that are annotated with XmlRootElement:
Here is another option, slight modification to another answer in above/below: