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?
Something like this perhaps:
You may want to take comments into account, but it shouldn't be too hard. You could also make sure you only look for imports before the class declaration.
I use DependencyFinder exactly for that purpose. It can analyse bytecode and extract all dependencies, then dump a report in txt or xml format (see the DependencyExtractor tool). You should be able to programatically analyse the report from your application's code.
I have integrated this in my build process in order to check that certain APIs are NOT used by an application.
I think the following might help you out:
You may want to use STAN for that.
The "Couplings View" visualizes the dependencies to your API in a nice graph.
If you use Eclipse. Try using the profiling tools. It doesn't only tells which classes are being used, but tells much more about it. The results will be something like:
There is a very good quickstart at:
http://www.eclipse.org/tptp/home/documents/tutorials/profilingtool/profilingexample_32.html