如何在运行时创建对象?

Boh*_*ian 4 java arrays

我需要在运行时创建一个类的许多不同对象.该数字也在运行时确定.

有点像我们在运行时获得int no_o_objects = 10.然后我需要实例化一个类10次.
谢谢

Jos*_*Lee 9

阅读Java教程中的数组.

class Spam {
  public static void main(String[] args) {

    int n = Integer.valueOf(args[0]);

    // Declare an array:
    Foo[] myArray;

    // Create an array:
    myArray = new Foo[n];

    // Foo[0] through Foo[n - 1] are now references to Foo objects, initially null.

    // Populate the array:
    for (int i = 0; i < n; i++) {
      myArray[i] = new Foo();
    }

  }
}
Run Code Online (Sandbox Code Playgroud)