如何计算内部 class 创建的对象数

how to count number of objects created of inner class

我有一个 activity,里面有一个名为 AsyncTask 的 class。在 AsyncTask class 内部,我想将计数器声明为静态变量,但我不能,因为 AsyncTask class 被假定为 mainActivity 的内部 class。

有什么方法可以在 AsycTask 中创建一个静态变量 "inner class" 来计算 AsyncTask 创建的对象的数量吗?

代码

class MainActivity extends Activity {
    ....
    ....
    ....
    ....

    class MyAsync extends AsyncTask <void, Void, Void> {

        private static int counter = 0; // is not possible here
    }

}

你可以这样做:

class MainActivity extends Activity {
    private static int counter = 0;

    // ...

    static class MyAsync extends AsyncTask <Void, Void, Void> {

        private MyAsync() {
            counter++;
        }

        // ...
    }
}

这样,每次创建 MyAsync 的新实例时,counter 都会递增。

您可以创建一个构造函数来递增 AsyncTask 中的 counter

这样做:

class MainActivity extends Activity {
....
....
....
....
    int counter = 0; 
    class MyAsync extends AsyncTask <void, Void, Void> {

       MyAsync()
       {
           counter++;
       }
    }

}

Logic behind this is : Constructor of any class will be called everytime when the new object of that will created. Inside constructor we have counter++ so each time when the new object is created the counter is incremented and You will have the count of number of objects created.

您也可以使用静态内部 class。

代码

class MainActivity extends Activity {
    ....
    ....
    ....
    ....

    static class MyAsync extends AsyncTask <void, Void, Void> {

        private static int counter = 0; // is not possible here
    }

}