2009-12-21 94 views
3

我需要在运行时创建许多不同类的对象。这个数字也是在运行时确定的。如何在运行时创建对象?

就像我们在运行时得到int no_o_objects = 10一样。 然后我需要实例化一个类10次。
谢谢

+12

对象仅在运行时创建。 – 2009-12-21 06:15:03

+2

我假设他意味着动态分配一个对象数组,这个数组的大小要在运行时确定。 – Anthony 2009-12-21 06:16:00

+0

是的,我的意思是动态分配一个对象数组 – Bohemian 2009-12-21 07:00:23

回答

9

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

    } 
} 
0

对象仅在运行创建。

试试这个:

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 
} 
0

这将做到这一点。

public AClass[] foo(int n){ 
    AClass[] arr = new AClass[n]; 
    for(int i=0; i<n; i++){ 
     arr[i] = new AClass(); 
    } 
    return arr; 
} 
0

您可以使用数组或List如下所示。

MyClass[] classes = new MyClass[n]; 

然后用new MyClass()在一个循环中实例化N个类别,并分配给classes[i]

-1

这是一个棘手的前瞻性问题,完美的解决方案是使用java反射。您可以创建对象并在运行时根据需要进行强制转换。此外,这种技术可以解决对象实例的数量问题。

这些都是很好的参考:在Java中

Reference1

Reference2