java 计算类的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5640272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count Instances of Class
提问by Charles
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.
我正在寻找一种方法来以编程方式获取 .NET 和 Java 中某个类类型的实例数。
Say for example I have class Foo. I want to be able to, in the same process, get a current count of all instance of Foo.
However I cannot modify Foo, so a static int with counting is out. Also I cannot just add all instances I make to some static list and count that. I want to be able to just say:
比如说我有 Foo 类。我希望能够在同一过程中获得所有 Foo 实例的当前计数。
但是我不能修改 Foo,所以一个带计数的静态 int 被淘汰了。此外,我不能只是将我制作的所有实例添加到某个静态列表中并对其进行计数。我只想说:
System.GC.numberOf< Foo >()
or something.
或者其他的东西。
I was looking through the garbage collectors but I could not find any relevant methods.
我正在查看垃圾收集器,但找不到任何相关方法。
采纳答案by mazaneicha
回答by Joshua Carmody
If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?
如果不能直接修改类(可能是因为它是内置类?),是否可以创建一个包装器,或者一个继承原始类的子类?
public class subFoo extends foo
{
protected static int count = 0;
public subFoo()
{
count++;
super();
}
protected void finalize() throws Throwable
{
count--;
super.finalize();
}
public static int getInstanceCount()
{
return count;
}
}
This example is Java and may have some syntax issues 'cause I'm a little rusty.
这个例子是Java,可能有一些语法问题,因为我有点生疏。
Of course, you'd have to be sure to redeclare all your foo
as subFoo
throughout the rest of your code.
当然,你必须确保重新声明所有foo
作为subFoo
整个代码的其余部分。
回答by Dilum Ranatunga
Do you have control of how the Java VM is being run? If so, you can write a quick and dirty debugger agent... http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#writingAgents
您是否可以控制 Java VM 的运行方式?如果是这样,您可以编写一个快速而肮脏的调试器代理... http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#writingAgents
See the events "VM Object Allocation" and "Object Free"
查看事件“VM Object Allocation”和“Object Free”
回答by user85421
As already commented, there are similar questions in SO.
One hack you can use - a big one IMO - is to changethe Object
class: see this answer
正如已经评论过的,SO中有类似的问题。
一个黑客可以使用-一个大的IMO -是要改变的Object
类:看到这个答案
Resume:
恢复:
- copy the source of Object
- add counting to its constructor (finalize)
- add method to read the count
- prepend the directory with the compiled class to the boot classpath (-Xbootclasspath)
- 复制对象的来源
- 向其构造函数添加计数(完成)
- 添加读取计数的方法
- 将带有编译类的目录添加到引导类路径 (-Xbootclasspath)
回答by Lupuss
Quick and dirty: if you can't change the class, maybe you can just put a counter in another part of the project, incrementing it when you instantiate said class?
快速而肮脏:如果你不能改变类,也许你可以在项目的另一部分放置一个计数器,当你实例化所述类时增加它?