UsAaR33 UsAaR33 - 1 year ago 93
Java Question

Get all classes referenced by a class

Let's say I have a java.lang.Class instance, c at runtime.

At runtime, is there anyway to see what classes are used by c? e.g. if instantiates a B, B is being 'used'. if calls static method, G is being used.

Note: Only trying to get what classes could be known statically - I'm fine missing ones loaded by reflection.

In python, equivalent functionality is found in modulefinder:

Answer Source

Everything that happens outside of method bodies, constructors and static initilizers can be queried with reflection. You can look at field and method signatures and reflect the fields to get the actual classes of field values.

Classes used inside methods are quite a challenge. You could use BCEL or a similiar tool to analyse the class file and extract all classnames that are hardcoded in the class file. But this will fail as soon as you program against interfaces:

public List someMethod() {
  return SomeClass.getList();

The type of the class returned by someMethod is not known by the class file. And there ist no lookup table or central registry. The JVM will know the type, look if the class is already loaded and - if not - try to load it. It doesn't have to care about which class asked for that other class and it will not record this information. Just because it is not needed for exectution and not needed for garbage collection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download