我尝试计算调用静态方法的频率,但不知道该怎么做,因为据我所知,我无法在静态方法中使用实例变量。 我有以下课程:
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
问候和感谢, 帕特里克
答案 0 :(得分: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 :(得分: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++;
}
}
答案 2 :(得分:1)
据我所知,我不能在静态方法中使用实例变量。
是的,但是字段也可以是静态的。
class Utilities {
private static int counter;
public static void showObject (Object o) {
System.out.println(++counter + ": " + o.toString());
}
}
答案 3 :(得分:1)
您可以使用以下内容:
private static final AtomicInteger callCount = new AtomicInteger(0);
,然后在您的方法中:
public static void showObject (Object o) {
System.out.println(callCount.incrementAndGet() + ": " + o.toString());
}
使用AtomicInteger
使计数器线程安全。
答案 4 :(得分:1)
您将要在static方法之外创建一个静态变量:
private static int counter = 0;
调用该方法时,增加变量:
public static void showObject(Object o){
System.out.println(counter + ": " + o);
counter++;
}
答案 5 :(得分:-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.
}
}