Search code examples
javaclassjvm.class-filelanguage-specifications

How to find out the dependent classes from a raw class file?


When I look at a binary class file can I easily find out what other classes need to be loaded in order to use this class?

As a sort of "directory" I can only see the Constant Pool Table with Class entries. The 1st and 2nd entry has a specific meaning, directly explained in the JVM Spec I found and elsewhere. But are the other entries in that table a list of other classes used by this class file? So to speak the JVM variant of the import-section of the *.java-file?

So it boils down to:

  • Do all Class entries in the constant pool table refer to a class that is used somewhere in the class file?
  • Or are there other mechanisms how a Class entry may get into the constant pool?
  • Assuming I wold not like to implement some kind of "lazy class loading" on first use of a class, am I therefore loading the correct list of used classes by using the class entries in the constant pool table?

Solution

  • Do all Class entries in the constant pool table refer to a class that is used somewhere in the class file?

    No, you can always put in constant pool entries that aren't actually used. A class compiled with a standard compiler will only contain entries that are actually used though.

    Or are there other mechanisms how a Class entry may get into the constant pool?

    No, the constant pool is fixed. Though the file on your disk may not represent the actual class that is loaded, since it's always possible for a custom class loader or Java agent to manipulate things at runtime.

    Assuming I wold not like to implement some kind of "lazy class loading" on first use of a class, am I therefore loading the correct list of used classes by using the class entries in the constant pool table?

    For static analysis, that's the best you can do. Note that you will miss dependencies used through reflection, but there's not much you can do about that.