How to get the instance of class
I have made three classes classA, classB and classC in the same开发者_JAVA百科 package. Now I make three objects of classA inside classB and two objects of classA inside classC. Now how can i get following things inside classA.
1) How many objects of classA has been used by classB and classC ? 2) How can i get the name & reference of the objects of classA which are in classB and classC?
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 :
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.
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 :)
You cannot, unless you supply a reference to the "owner" to the c'tor of each A object.
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).
If you did it like that (only code for 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. Only way is to instrument class A like Dominic suggested. But it will not tell you, how many A's exist, just how many A's have been created until now.
If you want more details, use one of the many profilers.
精彩评论