2009-12-21 117 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