简体   繁体   English

Java Reflection:通过输入名称来获取给定类的实例?

[英]Java Reflection: get instances of a given class found by entering its name?

Is it possible to get all instances of a class by entering this class's name as a string? 是否可以通过将此类的名称作为字符串输入来获取类的所有实例?

Something like this? 像这样的东西?

var instances = Reflection.findClass("com.someone.MyClass").getInstances();

Any feedback is appreciated. 任何反馈都表示赞赏。 Thanks. 谢谢。

No, there's nothing like that available. 不,没有那样可用。 If you hook into the debugging API you may be able to do it, but not when running "normally". 如果您挂钩到调试API,您可以这样做,但不能在“正常”运行时。

I don't know of a way of doing this at runtime, but, if you are happy doing it 'offline', you can do the following: 我不知道在运行时这样做的方法,但是,如果你很乐意“离线”,你可以执行以下操作:

  1. Take a heap dump 进行堆转储
  2. Load the heap dump into Eclipse MAT 将堆转储装载到Eclipse MAT中
  3. Open an OQL pane, and enter a command such as select * from com.someone.MyClass . 打开OQL窗格,然后输入命令,例如select * from com.someone.MyClass Running this query will return the instances in memory at the time that the heap dump was taken. 运行此查询将在执行堆转储时返回内存中的实例。

This is the sort of thing profilers are good for. 这是剖析器有用的东西。 With YourKit you can search for instances based on wildcarded class and inspect/navigate into them from largest to smallest or some other sort criteria. 使用YourKit,您可以根据通配类搜索实例,并从最大到最小或其他排序条件检查/导航它们。

This answer provides some options using various instrumentation APIs. 此答案提供了一些使用各种检测API的选项。 But these generally work on an application running in a separate JVM, and they entail stopping the JVM and trawling through all objects in the heap to find relevant instances. 但这些通常适用于在单独的JVM中运行的应用程序,它们需要停止JVM并在堆中的所有对象中进行拖网以查找相关实例。


A JVM does not keep any internal collections of all instances of each class. JVM不保留每个类的所有实例的任何内部集合。 But you can do this kind of thing yourself ... if you implement the behavior in each specific class or classes that you are interested in. You just need to be careful to avoid creating a memory leak by keeping references to instances that would otherwise be collectible garbage. 但是你可以自己做这样的事情......如果你在你感兴趣的每个特定类或类中实现行为。你只需要小心避免通过保留对实例的引用来创建内存泄漏。收藏垃圾。

The problem here is not finding the class object (this can be done by Class.forName() ), but that normally a class does not have any knowledge of its instances. 这里的问题不是找到类对象(这可以通过Class.forName()来完成),但通常一个类不知道它的实例。

If you have control over your class, you could create a registry of all instances, and add each instance to this in the constructor. 如果您可以控制您的类,则可以创建所有实例的注册表,并在构造函数中将每个实例添加到此实例中。 But you should be careful to not disable garbage collection by this, so use weak references instead of normal ones. 但是你应该小心不要禁用垃圾收集,所以使用弱引用而不是普通引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM