I have a String with some value. I want to iterate over all classes in a package calling a specific method, and if the value returned by the method is equals the value in my String, create an object of that class.
I want do this in a dynamic way, so if I add a class in this package, it will automatically be in the iteration.
Is possible do this? If not, there is a way to do what I want?
I was expecting something like.
for(Class clazz: SomeClass.listClasses("org.package")){
//code here
}
No, this is not possible in a totally reliable way; however, it may be practical to implement in many cases.
Due to the flexibility of Java class loaders, the classes defined under a particular package may not be known at runtime (e.g. consider a special classloader which defines classes on-the-fly, perhaps by loading them from the network, or compiling them ad-hoc). As such, there is no standard Java API which allows you to list the classes in a package.
Practically speaking, however, you could do some tricks by searching the classpath for all class and JAR files, building a collection of fully-qualified class names, and searching them as desired. This strategy would work fine if you are sure that no active classloader will behave as described in the previous paragraph. For example (Java pseudocode):