I'm trying to find a way to list which objects a run-time object is referring to. I know there is a way to enquire the jvm using oql but what I'd like to do is to query it from inside a program. Is there any API I could use?
How do I find what an object refers to?
418 Views Asked by uzilan At
2
You can do it via Reflection (
java.lang.reflect
).How is described in this article. Basically, given this class that has private members:
With Reflection, you can access all of its members (including the private ones), including their values. And so you look at all of its data members to see what they refer to (and of course, you can repeat the process if they also refer to other objects). Here's how to access their members (this code shows methods as well, which you probably won't need if you're just interested in data, but I didn't see any good reason to pull that part out):
I've fixed a bug in their original code and made a small change to make it more clear that
Hacker
is not in any way tied toSecret
(other than inmain
).Update: Re your question below about the fields from base classes, here's an updated
Hacker
that does that (I've assumed you don't want to try to enumerate the fields onObject
, so I've stopped there):When combined with
and
you get: