【问题标题】:How can i use a for loop to create objects with params?如何使用 for 循环创建带参数的对象?
【发布时间】:2022-11-25 10:08:48
【问题描述】:

我尝试在 for 循环中创建对象,例如:

String[] empArr[] = {
    {"Moe","Jude","Employee","2017"},
    {"Noe","Joel","Employee","2019"},
    {"Poe","Juce","Employee","2021"}
};

Employee[] emp;
emp = new Employee[empArr.length];
        
// get length and loop from empArr[], here there are 3 entries
for (int i=0; i<=empArr.length-1; i++) {
    // get length and loop from empArr[i], here there are 4 entries
    for (int j=0; j<=empArr[i].length-1; j++) {
        // create objects in loop from empArr[i] with params from empArr[i][0 ]
        emp[i] = new Employee(empArr[i][0],empArr[i][1],empArr[i][2],empArr[i][3]);
    }

    // create from a method the output and get here all firstNames from empArr[]
    output(emp[i].getInfo("firstName"));
}

这很有效,我得到了我想要的输出。 但我现在在中间部分使用:

for (int j=0; j<=empArr[i].length-1; j++) {
    emp[i] = new Employee(empArr[i][0],empArr[i][1],empArr[i][2],empArr[i][3]);
}

是否也有可能为对象的参数创建一个 j 循环? 就像是:

emp[i] = new Employee(
    for (int j=0; j<=empArr[i].length-1; j++) {
        empArr[i][j];
    }
);

我试过上面的这段代码,但我无法让它工作: 我无法想象解决方案,希望得到帮助

此致

【问题讨论】:

  • 不,没有办法做这种缺乏反思的事情——你也不想那样做。代码不会更短,也不会变得更难维护,而不是更容易。尝试将数据文件(csvs、xmls、jsons、yamls)编组到对象中很容易,只是 - 不是这种方式。查找 jackson、GSON 等。
  • 感谢您的回答和提示,我会搜索的
  • 我希望看到 Java 默认有一些方法来做到这一点。 Java 已经能够使用 XML 编组数据很长时间了,我认为是时候将 JSON 添加到默认 API 中了。综上所述,您确定需要第二个内部循环吗?你只需要在这里创建四个对象,对吧?我认为您实际上是在创建十六个对象,每四个对象都是另一个对象的副本。

标签: java for-loop object arguments new-object


【解决方案1】:

我想你要找的是factory design pattern

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2012-12-27
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多