-6

如何判断一个方法是否被调用,以便我可以添加一个计数器来测量该方法的总调用次数?

编辑澄清。

假设我有

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

我在 main 方法中创建了任何东西的实例 3 次,如果我调用它的 toString() 整个 3 次,我想要的输出是这样的:

  • 调用此方法的时间为 1
  • 调用此方法的时间为 2
  • 调用此方法的时间是 3

我希望将计数器成功添加到类中和 ToString() 方法中,而不是在 main 中。

提前致谢。

4

4 回答 4

3

您可以使用私有实例变量计数器,您可以在每次调用您的方法时递增:-

public class Demo {
    private int counter = 0;

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

更新 : -

根据您的编辑,您需要一个在实例之间共享的静态变量。因此,一旦您更改了该变量,它将针对所有实例进行更改。它基本上绑定到类而不是任何实例。

因此,您的代码应如下所示: -

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; 
    }
}   
于 2012-11-25T13:07:20.913 回答
1

你有2个选择...

计算一个实例的消息:

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;
}
}

或者计算所有创建实例的全局调用:

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;
}
}
于 2012-11-25T13:10:51.233 回答
1

最好的方法是使用私有整数字段

private int X_Counter = 0;

public void X(){
    X_Counter++;
    //Some Stuff
}
于 2012-11-25T13:11:28.107 回答
0

这取决于你的目的是什么。如果在您的应用程序中,您想使用它,那么在每个方法中都有一个计数器来提供详细信息。

但是,如果它是一个外部库,那么像 VisualVM 或 JConsole 这样的分析器将为您提供每种方法的调用次数。

于 2012-11-25T13:10:40.497 回答