计算在Java中调用静态方法的频率
我试图计算静态方法被调用的频率,但不知道如何执行,因为据我所知,我无法在静态方法中使用实例变量。 我有以下课程:计算在Java中调用静态方法的频率,java,methods,count,static,Java,Methods,Count,Static,我试图计算静态方法被调用的频率,但不知道如何执行,因为据我所知,我无法在静态方法中使用实例变量。 我有以下课程: 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.
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
问候和感谢,
Patrick您可以使用静态变量来计算调用该方法的次数
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;
}
}
将静态计数器添加到类:
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++;
}
}
据我所知,我不能在静态方法中使用实例变量
是的,但是字段也可以是静态的
class Utilities {
private static int counter;
public static void showObject (Object o) {
System.out.println(++counter + ": " + o.toString());
}
}
您可以使用以下选项:
private static final AtomicInteger callCount = new AtomicInteger(0);
然后在你的方法中:
public static void showObject (Object o) {
System.out.println(callCount.incrementAndGet() + ": " + o.toString());
}
使用
AtomicInteger
可以使计数器线程安全。您需要在静态方法之外创建一个静态变量:
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.
}
}
private static int counter = 0;
调用方法时,递增变量:
public static void showObject(Object o){
System.out.println(counter + ": " + o);
counter++;
}
静态变量呢?简单吗?你是说主方法中的静态变量?我考虑过这个问题,但问题是我有4个不同的文件(4个不同的类),它们都允许使用showObject方法。所以我想增加showObject方法中的计数器,以确保每次调用它时它都计数。showObject方法中的静态变量在该方法结束时会“消亡”,对吗?你是什么意思