2012-07-10 181 views
0

我有一個方法接收一個字符串數組,我需要創建具有適當名稱的對象。動態創建對象

例如:

public class temp {  
    public static void main(String[] args){ 

    String[] a=new String[3]; 
    a[0]="first"; 
    a[1]="second"; 
    a[2]="third"; 
    createObjects(a); 

    } 
    public static void createObjects(String[] s) 
    { 
    //I want to have integers with same names 
    int s[0],s[1],s[2]; 
    } 
} 

如果我收到( 「一」, 「二」),我必須創建:

Object one; 
Object two; 

如果我收到( 「男孩」, 「女孩」),我必須創建:

Object boy; 
Object girl; 

任何幫助,將不勝感激。

+0

也許您還沒有使用Java中的* collection framework *。 – Lion 2012-07-10 10:57:20

+1

你是什麼意思,「用適當的名字」?你是否試圖創建具有名稱屬性的對象?或者你真的想要叫「第一」,「第二」等類?你試過什麼了? – 2012-07-10 10:57:23

+1

「int」不是一個對象! – doNotCheckMyBlog 2012-07-10 10:57:52

回答

7

在java中不能這樣做。您可以改爲創建一個Map誰的鍵是字符串,值是對象。

+0

,但我不知道用哪個名稱創建對象,只有在執行 – temcheg 2012-07-10 11:05:07

+0

時才知道映射是在運行時填充的。 – vainolo 2012-07-10 11:27:26

0

首先創建Map其中包含作爲字符串表示Integers的密鑰。

public class Temp { 

static Map<String, Integer> lMap; 

static { 

    lMap = new HashMap<String, Integer>(); 
    lMap.put("first", 1); 
    lMap.put("second", 2); 
    lMap.put("third", 3); 
} 

public static void main(String[] args) { 
    Map<String, Integer> lMap = new HashMap<String, Integer>(); 
    String[] a = new String[3]; 
    a[0] = "first"; 
    a[1] = "second"; 
    a[2] = "third"; 

    Integer[] iArray=createObjects(a); 
    for(Integer i:iArray){ 

     System.out.println(i); 
    } 

} 

public static Integer[] createObjects(String[] s) { 
    // I want to have integers with same names 
    Integer[] number = new Integer[s.length]; 
    for (int i = 0; i < s.length; i++) { 
     number[i] = lMap.get(s[i]); 
    } 
    return number; 
} 

} 
+0

你誤會了我:)整數就是例子。我的意思是: 如果我收到(「one」,「two」),我必須創建: Object one; 對象二; 如果我收到(「男孩」,「女孩」),我必須創建: 對象男孩; 對象女孩; – temcheg 2012-07-10 13:43:47