繁体   English   中英

如何判断一个方法是否被调用?

[英]How can I tell if a method is being called?

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

编辑以澄清。

假设我有

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 中。

提前致谢。

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

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

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

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

private int X_Counter = 0;

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

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

但是如果它是一个外部库,那么像 VisualVM 或 JConsole 这样的分析器会给你每个方法的调用次数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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