java 如何在运行时创建对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1938482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create objects at runtime?
提问by Bohemian
I need to make a number of distinct objects of a class at runtime. This number is also determined at runtime.
我需要在运行时创建一个类的许多不同的对象。这个数字也是在运行时确定的。
Something like if we get int no_o_objects=10 at runtime.
Then I need to instantiate a class for 10 times.
Thanks
就像我们在运行时得到 int no_o_objects=10 一样。然后我需要实例化一个类 10 次。
谢谢
回答by Josh Lee
Read about Arrays in the Java Tutorial.
阅读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();
}
}
}
回答by Prasoon Saurav
Objects in Java are only created at Runtime.
Java 中的对象仅在运行时创建。
Try this:
试试这个:
Scanner im=new Scanner(System.in);
int n=im.nextInt();
AnyObject s[]=new AnyObject[n];
for(int i=0;i<n;++i)
{
s[i]=new AnyObject(); // Create Object
}
回答by Erkan Haspulat
This would do it.
这样就可以了。
public AClass[] foo(int n){
AClass[] arr = new AClass[n];
for(int i=0; i<n; i++){
arr[i] = new AClass();
}
return arr;
}
回答by fastcodejava
You can use array or Listas shown below.
您可以使用数组或List如下所示。
MyClass[] classes = new MyClass[n];
Then instantiate n classes with new MyClass()in a loop and assign to classes[i].
然后new MyClass()在循环中实例化 n 个类并分配给classes[i].
回答by Malintha
This is an straingth forward question and the perfect solution is using java reflection. You can create objects and cast them as need while the runtime. Also the number of object instances can be solved with this technology.
这是一个棘手的问题,完美的解决方案是使用 java 反射。您可以在运行时创建对象并根据需要转换它们。此外,该技术可以解决对象实例的数量问题。
These are good references:
这些是很好的参考:

