System.out.println(javaClass.getSuperclassName());
JavaClass javaClass1 = javaClass.getSuperClass();
the first line output the name of the class: RestController
The second line throws Exception:
java.lang.ClassNotFoundException: Exception while looking for class example.RestController: java.io.IOException: Couldn't find: example/RestController.class
So, you're using The Byte Code Engineering Library (Apache Commons BCEL™) to load classes from a Jar file (by filename) and want to print the entire call graph with the following github project.
This works just fine, until you want to ask for the
superclassof a class that was found in your jar file.So
bcelwill load a .class file, and store all it can read from the class file in aJavaClassmodel. This is for example the name, some flags, the super class name, the declared methods etc.For example inspect the following java code;
with output:
So bcel knows that the superclass is
java.lang.Object, but it has not loaded any of the classes at this point! For JRE classes this is of course moot, but for the classes from your Jar file this is a problem.Because
org.apache.bcel.classfile.JavaClass#getSuperclassNamewill just return theStringvalue that it found as the super class in the .class file. Again this class was not loaded, so theRepositorydoesn't know about it.When you then ask for the
org.apache.bcel.classfile.JavaClass#getSuperClass, it will try to find it like so:Bcel will try to load it from its
Respository, and if the class is unknown, it will delegate the loading to the currentClassPath. Since you're just inputting aFilepointing to a Jar, this will fail with theClassNotFoundException.There are two ways to you can solve this:
Put the jar file(s) on your classpath; for example via Including all the jars in a directory within the Java classpath
First load all the jar files into the
Repositoryof bcel, so that it knows these classes exist. If we stay in theJCallGraphexample from github, that would look something like this:Note that if you have multiple jar files, or super classes coming from external dependencies, these all need to be on the classpath (1) or loaded in bcel first (2) before you can load the superclass.