I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information. To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods. This is proving to be near impossible.
I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.
EDIT: I think I phrased this poorly. My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly. My issue is obtaining a Class object for each class file.
List All the classes inside jar file.
The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.
edit:
As suggested in the comments above, javassist would also be a possibility. Initialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:
From the ctClass, you can get all methods, fields, nested classes, .... Take a look at the javassist api: https://jboss-javassist.github.io/javassist/html/index.html
Scanning all of the files in a folder is simple. One option is to call
File.listFiles()
on theFile
that denotes the folder, then iterate the resulting array. To traverse trees of nested folders, use recursion.Scanning the files of a JAR file can be done using the
JarFile
API ... and you don't need to recurse to traverse nested "folders".Neither of these is particularly complicated. Just read the javadoc and start coding.