Java 如何计算显式创建的继承树中特定类的实例数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21013349/
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
How to count the number of instances of a particular class in inheritance tree, created explicitly?
提问by sudhir
class A {
static int i;
{
System.out.println("A init block"+ ++i);
}
}
class B extends A {
static int j;
{
System.out.println("B init block"+ ++j);
}
}
class C extends B {
static int k;
{
System.out.println("C init block"+ ++k);
}
public static void main(String abc[])
{
C c =new C();
}
}
In the code above, we can easily count the number of objects created for each class. But if i want to check the number of object created explicitly , i mean if I create C's object using new C(), or B's object using new B(), then it should give the count accordingly
在上面的代码中,我们可以轻松计算为每个类创建的对象数量。但是如果我想检查显式创建的对象的数量,我的意思是如果我使用 new C() 创建 C 的对象,或者使用 new B() 创建 B 的对象,那么它应该相应地给出计数
Take for example,
举个例子,
C c2=new C();
B b2=new B();
So it should give the output of B's count as 1 and not 2.
所以它应该将 B 的计数输出为 1 而不是 2。
采纳答案by JB Nizet
public class Foo {
private static int fooCount = 0;
public Foo() {
if (this.getClass() == Foo.class) {
fooCount++;
}
}
public static int getFooCount() {
return fooCount;
}
}
回答by TheLostMind
public class Test {
static int count;
Test() {
count++;
}
public static void main(String[] args) {
Test t = new Test();
Test t1 = new Test();
NewTest nt = new NewTest();
System.out.println("Test Count : " + Test.count);
System.out.println("NewTest Count : " + NewTest.count);
}
}
class NewTest extends Test
{ static int count;
NewTest()
{
Test.count--;
NewTest.count++;
}
}
OP :
操作:
Test Count : 2
NewTest Count : 1