如何在运行时创建对象?
我需要在运行时创建一个类的许多不同对象。 该数字也在运行时确定。
有点像我们在运行时获得int no_o_objects = 10。 然后我需要实例化一个类10次。
谢谢
阅读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(); } } }
Java中的对象仅在运行时创建。
尝试这个:
Scanner im=new Scanner(System.in); int n=im.nextInt(); AnyObject s[]=new AnyObject[n]; for(int i=0;i
这样做会。
public AClass[] foo(int n){ AClass[] arr = new AClass[n]; for(int i=0; i
您可以使用如下所示的数组或List
。
MyClass[] classes = new MyClass[n];
然后在循环中使用new MyClass()
实例化n个类并分配给classes[i]
。
这是一个棘手的问题,完美的解决方案是使用javareflection。 您可以在运行时创建对象并根据需要进行转换。 此外,可以使用此技术解决对象实例的数量。
这些是很好的参考:
定1
定2