SanityCheck
SanityCheck

Reputation: 169

Java byte/source code analysis - how do I find all the classes/methods that use another class - programmatically?

I need to know programmatically what classes are calling a given class's (say X) getters and setters. The key thing here is 'programmatically'.

For example, if class A uses X's setPropertyABC() and class B uses X's getPropertyABC(), I would like to define dependency between classes based on their calls to X - in this case, Class A's execution has to precede Class B.

I need to do this programmatically (not through an IDE). I want to create a program that will look at the compiled byte codes or source code of the classes and figure out which classes are using what methods on a given class. What is the best Java library to use for this purpose? Are byte code tools more appropriate? I was thinking if ANTLR can do this job but I am not sure. Is there any sample code in public domain that solves this problem?

Upvotes: 1

Views: 1119

Answers (3)

SanityCheck
SanityCheck

Reputation: 169

After considering all the alternatives, I have decided to go with ASM library for byte code analysis. It has proven to be quite apt and useful. Thank you all for your responses.

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163262

I did an exercise some years ago analysing dependencies at source code level using a tool called Dependency Finder. I reported on the project at http://dev.saxonica.com/blog/mike/2009/09/analyzing-dependencies-in-a-class-library-a-use-case-for-xslt-streaming.html

The tool outputs information (in XML form) about dependencies between modules and is configurable as regards the granularity of reporting. I did a fair bit of analysis of the XML reports (using XSLT) to get the understanding I needed of the code structure, which in this case was the entire OpenJDK library.

The blog is focussed on how to do the analysis of some very large XML files, but I hope it will give you some insights.

The public comments on the blog article also point to a couple of other dependency analysis tools.

Upvotes: 0

Lucas Ross
Lucas Ross

Reputation: 1089

Maybe you could use Aspects. You'd have a pointcut that intercepts all of the class's get* and set* methods. The advisor could use Thread.currentThread().getStackTrace() to figure out what the calling method was and then log the findings. This isn't exactly a bytecode analysis technique but is probably more straightforward.

[edit] And as far as computing a sort of temporal dependency between two classes, one of which relies upon a setter being called by something else, your advisor could append info about every call to some kind of insertion-order data structure (LinkedHashMap). If a getX is called, then you look at what calls to setX have been made.

Upvotes: 1

Related Questions