CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Getting count of objects of a class in Java!

The following article explains how to maintain reference count of objects whenever instance of a class is created. Some times it will be useful to get to know the number of instances are created for a class; this article will be useful.

Step (1). Create your own class and make sure add the following private static member.

private static AtomicInteger countRef = new AtomicInteger();

Step (2). Make sure to increment the member in the constructor of a class.

countRef.getAndIncrement();

Step (3). Decrements the member when the object is going to be destroyed by the Garbage Collector. Best place to add the following statement is in finalize() method of a class.

countRef.getAndDecrement();

Step (4). Add new public static method to the class to get the reference count.

public static int getRefCount()
{
return countRef.get();
}

Step (5). Once your new class is ready, instantiate the class and get the reference count by calling class’s getRefCount method.

Look at the full example below (MyClass.java):

// -- Import(s)
import java.util.concurrent.atomic.AtomicInteger;

// -- MyClass
public class MyClass
{
// --
private static AtomicInteger countRef = new AtomicInteger();

// Class constructor.
public MyClass()
{
countRef.getAndIncrement();
}
// -- finalize Method for any cleanup things.
protected void finalize() throws Throwable
{
countRef.getAndDecrement();
}

// -- Method to get object reference count.
public static int getRefCount()
{
return countRef.get();
}

// -- Test getRefCount function
public static void main(String[] args)
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();

System.out.println("Number of Instances of a class MyClass : " + MyClass.getRefCount());
}
}

Compile: javac MyClass.java

Run: java MyClass

There are several ways to achieve this. Hope this is also helpful.

Getting count of objects of a class in Java!

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top