Count how often static method is called in Java

AtMakeIT :

I try to count how often a static method is called and do not know how to do it, since I can not use an instance variable within the static method as far as I know. I have the following class:

public class Utilities {

     // print how often method was called + specific Value of Object o
     public static void showObject (Object o) {
          System.out.println(counter + ": " + o.toString());
     }
}

Printing the objects-values works, but how can I make the counter count? So the result for the following code should look like this:

    public static void main (String[] args){
    Object objectA = new Object ("Object A", 4);
    Object objectB = new Object ("Object B", 4);
    Object objectC = new Object ("Object C", 4);

    Utilities.showObject(objectB);
    Utilities.showObject(objectC);
    Utilities.showObject(objectC);
    Utilities.showObject(objectA);


1: 3.6
2: 8.0
3: 8.0
4: 9.2

Greetings and thanks, Patrick

Benjamin Urquhart :

You're going to want to create a static variable outside of the static method:

private static int counter = 0;

When the method is called, increment the variable:

public static void showObject(Object o){
    System.out.println(counter + ": " + o);
    counter++;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143999&siteId=1