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];
   }
}

如果我收到 ("one","two") 我必须创建:

Object one;
Object two;

如果我收到 ("boy","girl") 我必须创建:

Object boy;
Object girl;

任何帮助,将不胜感激。

4

2 回答 2

7

在java中无法做到这一点。您可以改为创建Map谁的键是字符串,值是对象。

于 2012-07-10T10:55:57.837 回答
0

First create Map which contains the key as String representation of 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;
}

}
于 2012-07-10T11:13:08.623 回答