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
Remapper
class (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
Remapper
whose 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:
Thanks Adam Paynter, It helped me. But what I was looking for is to fetch the dependent classes (recursively)- which means take a feature from a projects. So, need to get all the classes associated with a particular classes and again the used classes of those classes and so on. and also get the jars. So, I Created my own Java Dependency Resolver project Which will find the dependent Classes/jars for a particular class in a Project. I am sharing it here that may come to any use of some body.