计算在Java中调用静态方法的频率

问题描述 投票:2回答:6

我试着计算一个静态方法被调用的频率并且不知道如何去做,因为据我所知,我不能在静态方法中使用实例变量。我有以下课程:

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

打印对象值有效,但如何计算计数器?因此,以下代码的结果应如下所示:

    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

亲爱的,谢谢,帕特里克

java methods count static
6个回答
1
投票

您将要在静态方法之外创建静态变量:

private static int counter = 0;

调用该方法时,增加变量:

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

1
投票

您可以使用静态变量来计算调用方法的次数。

public class Utilities {

     private static int count;

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

     // method to retrieve the count
     public int getCount() {
         return count;
     }
}

1
投票

在您的班级添加静态计数器:

public class Utilities {

     // counter where you can store info
     // how many times method was called
     private static int showObjectCounter = 0;

     public static void showObject (Object o) {
          // your code

          // increment counter (add "1" to current value")
          showObjectCounter++;
     }
}

1
投票

据我所知,我不能在静态方法中使用实例变量。

没错,但字段也可以是静态的。

class Utilities {

    private static int counter;

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

}

1
投票

您可以使用以下内容:

private static final AtomicInteger callCount = new AtomicInteger(0);

然后在你的方法中:

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

使用AtomicInteger使计数器线程安全。


-1
投票
public class Utilities {
     static int counter = 0; // when the method is called counter++
     public static void main (String[] args) {
               showObject(null);
               showObject(null); //it is probably a very bad idea to use null but this is an example
               System.out.println(counter);
     }
     public static void showObject (Object o) {
          System.out.println(counter + ": " + o.toString());
          counter++; // method was called. Add one.
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.