简体   繁体   English

如何获取类的实例

[英]How to get the instance of class

I have made three classes classA, classB and classC in the same package. 我在同一包中制作了三个类classA,classB和classC。 Now I make three objects of classA inside classB and two objects of classA inside classC. 现在,我在classB中创建了三个classA对象,在classC中创建了两个classA对象。 Now how can i get following things inside classA. 现在我该如何在classA中进行跟踪。

1) How many objects of classA has been used by classB and classC ? 1)classB和classC使用了多少个classA对象? 2) How can i get the name & reference of the objects of classA which are in classB and classC? 2)如何获取classB和classC中classA对象的名称和引用?

For the total number of instances, you could have a static variable in class A. A static variable is a variable which is based on the class itself rather then the instance and is defined like so : 对于实例总数,类A中可以有一个静态变量。静态变量是基于类本身而不是实例的变量,其定义如下:

private static int totalInstances = 0;

And then in the constructor of class A, you would just increment that variable, and decrement it in the destructor. 然后,在类A的构造函数中,您只需增加该变量,然后在析构函数中将其减小。

You could then make an accessor for this variable 然后,您可以为此变量创建访问器

public int getTotalInstances(){
    return totalInstances;
}

And you would then be able to get the total ammount of instances like so : 然后,您将能够获得实例的总数,如下所示:

classA.getTotalInstances()

Make sure to make it the class name rather than the instance name. 确保将其设置为类名而不是实例名。

If you wanted to keep track of the reference variables, you could create a static array of reference variables, and add the reference every time an object was created in the same manner we incremented the total instances :) 如果您想跟踪参考变量,则可以创建一个参考变量的静态数组,并在每次创建对象时都以与增加实例总数相同的方式添加参考:)

除非您为每个A对象的所有者提供对“所有者”的引用,否则不能这样做。

If you did it like that: 如果您那样做:

public class B {
  private a1 = new A();
  private a2 = new A();
  private a3 = new A();
}

public class C {
  private a1 = new A();
  private a2 = new A();
}

, then you could use the reflection API to look for class members of type A and count all non-null members of that type and reflect the A instances to get the object names (assume, you have a sort of A#getName() method). ,则可以使用反射API查找类型A的类成员,并计算该类型的所有非空成员,并反映A实例以获取对象名称 (假设您有一种A#getName()方法)。

If you did it like that (only code for B): 如果您这样做(仅针对B代码):

public class B {
   public B() {
     new A();
     new A();
     new A();
   }
 }

, there's no chance to 'look at a B instance' and tell, how many A's have been created. ,就没有机会“看一下B实例”并告诉您已经创建了多少个A。 Only way is to instrument class A like Dominic suggested. 唯一的办法就是像Dominic建议的那样对A类乐器进行演奏。 But it will not tell you, how many A's exist, just how many A's have been created until now. 但是它不会告诉您,存在多少个A,到现在为止已经创建了多少个A。

If you want more details, use one of the many profilers. 如果需要更多详细信息,请使用许多探查器之一。

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

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