如何找到对象所指的内容?
我正在尝试找到一种方法来列出运行时对象所引用的对象。我知道有一种方法可以使用 oql 查询 jvm,但我想做的是从程序内部查询它。有我可以使用的 API 吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过反射来完成此操作(
java.lang.reflect
)。本文如何描述。基本上,给定此类具有私有成员:
通过反射,您可以访问其所有成员(包括私有成员),包括它们的值。因此,您查看其所有数据成员以了解它们引用的内容(当然,如果它们还引用其他对象,您可以重复该过程)。以下是如何访问他们的成员(此代码也显示了方法,如果您只对数据感兴趣,您可能不需要这些方法,但我没有看到任何充分的理由将该部分拉出来):
我已经修复他们的原始代码中存在一个错误,并进行了一些小更改,以更清楚地表明
Hacker
与Secret
没有任何关系(除了main
中)代码>)。更新:关于下面关于基类字段的问题,这是一个更新的
Hacker
,它可以做到这一点(我假设您不想尝试枚举字段在Object
上,所以我就停在那里了):当与 结合时
,
你会得到:
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:
您可以使用Object类的getClass()方法来获取对象的运行时类。
You can use getClass() method of Object class to get the runtime class of an object.