如何在运行时创建对象? [英] How do I create objects at runtime?

查看:38
本文介绍了如何在运行时创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to make a number of distinct objects of a class at runtime. This number is also determined at runtime.

类似于在运行时获取int no_o_objects = 10的情况. 然后我需要实例化一个类10次.
谢谢

Something like if we get int no_o_objects=10 at runtime. Then I need to instantiate a class for 10 times.
Thanks

推荐答案

阅读有关 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();
    }

  }
}

这篇关于如何在运行时创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆