In a Java Project of mine, I would like to find out programmatically which classes from a given API are used. Is there a good way to do that? Through source code parsing or bytecode parsing maybe? Because Reflection won’t be of any use, I’m afraid.
To make things simpler: there are no wildcard imports (import com.mycompany.api.*;) anywhere in my project, no fully qualified field or variable definitions (private com.mycompany.api.MyThingy thingy;) nor any Class.forName(...) constructs. Given these limitations, it boils down to parsing import statements, I guess. Is there a preferred approach to do this?
You can discover the classes using ASM‘s
Remapperclass (believe it or not). This class is actually meant to replace all occurrences of a class name within bytecode. For your purposes, however, it doesn’t need to replace anything.This probably doesn’t make a whole lot of sense, so here is an example…
First, you create a subclass of
Remapperwhose only purpose in life is to intercept all calls to themapType(String)method, recording its argument for later use.Now you can write a method like this:
It’s your responsibility to actually obtain all classes’ bytecode.
EDIT by seanizer (OP)
I am accepting this answer, but as the above code is not quite correct, I will insert the way I used this:
Here’s a main class to test it using:
And here’s the Output: