Java 动态创建对象
我有一个接收字符串数组的方法,我需要创建具有适当名称的对象 例如:Java 动态创建对象,java,Java,我有一个接收字符串数组的方法,我需要创建具有适当名称的对象 例如: 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
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;
如果我收到(“男孩”、“女孩”),我必须创建:
Object one;
Object two;
Object boy;
Object girl;
任何帮助都将不胜感激。在java中无法做到这一点。您可以创建一个
映射
谁的键是字符串,谁的值是对象。首先创建映射
,其中包含键作为整数的字符串表示形式
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;
}
}
公共类临时{
静态映射lMap;
静止的{
lMap=newhashmap();
lMap.put(“第一”,1);
lMap.put(“第二”,2);
lMap.put(“第三”,3);
}
公共静态void main(字符串[]args){
Map lMap=newhashmap();
字符串[]a=新字符串[3];
a[0]=“第一”;
a[1]=“秒”;
a[2]=“第三”;
整数[]iArray=createObjects(a);
for(整数i:iArray){
系统输出打印LN(i);
}
}
公共静态整数[]createObjects(字符串[]s){
//我想要有相同名字的整数
整数[]编号=新整数[s.length];
对于(int i=0;i
您可能还没有使用Java中可用的集合框架。您说的“使用适当的名称”是什么意思?您正在尝试创建具有name属性的对象吗?或者你真的想让课程名为“第一”、“第二”等等?到目前为止,您尝试了什么?但我不知道使用哪些名称创建对象,只有在执行时才会知道。映射是在运行时填充的。您误解了我:)整数就是示例。我的意思是:如果我收到(“一”,“二”),我必须创建:对象一;对象二;如果我收到(“男孩”、“女孩”),我必须创建:对象男孩;对象女孩;