Is it possible to iterate over all classes inside a package using Reflection?

I have a string with some value. I want to iterate over all the classes in a package that calls a particular method, and if the value returned by the method is equal to the value in my string, create an object of this class.

I want to do this dynamically, so if I add a class to this package, it will be automatically iterated.

Is it possible? If not, is there a way to do what I want?


I was expecting something like.

for(Class clazz: SomeClass.listClasses("org.package")){ //code here } 
+8
java reflection
source share
3 answers

No, this is not possible in an absolutely reliable form; however, in many cases this can be practical.

Due to the flexibility of Java class loaders, the classes defined in a particular package may not be known at run time (for example, consider a special class loader that defines classes on the fly, possibly downloading them from the network or compiling them ad-hoc). Thus, there is no standard Java API that allows you to list classes in a package.

In practice, however, you could do some tricks by searching for class paths for all classes and JAR files, creating a collection of fully qualified class names and doing the search as you wish. This strategy will work fine if you are sure that no active class loader will behave as described in the previous paragraph. For example (Java pseudo code):

 Map<String, Set<String>> classesInPackage = new HashMap(); for (String entry : eachClasspathEntry()) { if (isClassFile(entry)) { String packageName = getPackageName(entry); if (!classesInPackage.containsKey(packageName)) { classesInPackage.put(packageName, new HashSet<String>()); } classesInPackage.get(packageName).add(getClassName(entry)); } else if (isJarOrZipFile(entry)) { // Do the same for each JAR/ZIP file entry... } } classesInPackage.get("com.foo.bar"); // => Set<String> of each class... 
+8
source share

I can think of two ways to solve what, in my opinion, is your problem, although it’s not really going to sort through all the classes in the package.

One of them is to create a separate file that lists the classes this particular method should be called on. This is pretty easy to implement. You may have work to create a file, but it can be automated.

The second option is to look for .class files in a known place - say, a single folder or set of folders - and guess what the class name is and load it. If this is a simple development process, class files from the same package are probably in the same directory.

+2
source share

Yes, but not as a solution in the general case. You will have to package your code and invoke the JVM in a certain way. In particular, you need to create an Instrumentation agent and call java.lang.instrument.Instrumentation.getAllLoadedClasses() .

The documentation for java.lang.instrument contains detailed information on how to create and create an agent instance.

+1
source share

All Articles