簡體   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