4 回答
TA贡献1757条经验 获得超7个赞
您将要在静态方法之外创建一个静态变量:
private static int counter = 0;
调用该方法时,递增变量:
public static void showObject(Object o){
System.out.println(counter + ": " + o);
counter++;
}
TA贡献1851条经验 获得超4个赞
您可以使用静态变量来计算方法被调用的次数。
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;
}
}
TA贡献1784条经验 获得超8个赞
将静态计数器添加到您的班级:
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++;
}
}
TA贡献2021条经验 获得超8个赞
您可以使用以下内容:
private static final AtomicInteger callCount = new AtomicInteger(0);
然后在你的方法中:
public static void showObject (Object o) { System.out.println(callCount.incrementAndGet() + ": " + o.toString()); }
使用AtomicInteger
使计数器线程安全。
添加回答
举报