Let's say I have the following classes:

class A {
  static public String a;

class B {
  public function referToFieldInClassA() {

Is there anything in the Java reflection APIs to allow me to find all places where a particular field is referenced? What I'm looking for is a way to find out that (given the example) class B has a reference to A.a.

I know I can get all the Fields in a Class via the reflection API. But now I want to find all references to that Field.


+2  A: 

From the standard APIs, I think the answer is no. Eclipse can do it, but that's not at runtime.

For an incredibly hack-ish way of doing it, get the ClassLoader object, get the resourceAsStream to get something, use something like JODE to decompile it, and parse the source from inside of the program.

But that's a crazy amount of work. What the heck are you using this for?

Dean J
I suspect its because he wants to encapsulate a field by changing direct access to getters / setters without realizing that most IDE's will do this automatically.
Thanks for the comments. I'm actually way beyond what the IDE can do for me. I'm building a dependency graph of my application and storing it in a relational database so that the dependencies can be analyzed offline. So, it would be like taking what the IDE does for me and save the output to a database. I used Dependency Finder to give me all method dependencies quite nicely. Now I'm looking for a clean way to do fields as well. Dependency Finder can do it, as long as the fields aren't final. So that's what I think I'll end up doing. Thanks for the comments though.
Laran Evans
+1  A: 

If your need is compile-time rather than run-time, and you don't have an IDE, the very old trick of changing the names of the fields and recompiling, and searching for what fails to compile. ;]

Then, of course, get yourself an IDE.