简体   繁体   中英

How can I tell if a method is being called?

How can I tell if a method is being called so that I can add a counter to measure the total calls of this method?

Edit for clarification.

assuming that I have

class anything{ 
public String toString() { 
++counter; 
return "the time this method is being called is number " +counter; 
} 
}//end class 

and I am creating an instance of anything in a main method 3 times, and the output I want if I call its toString() the whole 3 times is this:

  • the time this method is being called is number 1
  • the time this method is being called is number 2
  • the time this method is being called is number 3

I want the counter being added succesfully inside the class and inside the ToString() method and not in main.

Thanks in advance.

You can use a private instance variable counter, that you can increment on every call to your method: -

public class Demo {
    private int counter = 0;

    public void counter() {
        ++counter;
    }
}

Update : -

According to your edit, you would need a static variable, which is shared among instances. So, once you change that varaible, it would be changed for all instances. It is basically bound to class rather than any instance.

So, your code should look like this: -

class Anything {   // Your class name should start with uppercase letters.
    private static int counter = 0;

    public String toString() { 
        ++counter; 
        return "the time this method is being called is number " +counter; 
    }
}   

You have 2 options...

Count the messages for one instance:

public class MyClass {
private int counter = 0;

public void counter() {
    counter++;
    // Do your stuff
}

public String getCounts(){
    return "The time the method is being called is number " +counter;
}
}

Or count the global calls for all created instances:

public class MyClass {
private static int counter = 0;

public void counter() {
    counter++;
    // Do your stuff
}
public static String getCounts(){
    return "the time the method is being called is number " +counter;
}
}

The best way to do this is by using a private integer field

private int X_Counter = 0;

public void X(){
    X_Counter++;
    //Some Stuff
}

It depends on what your purpose is. If inside you application, you want to use it, then have a counter inside every method to give details.

But if its an external library, then profilers like VisualVM or JConsole will give you number of invocations of each method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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