我一直在努力让我的代码更高效,但我遇到了一个问题,我必须多次重复自己才能创建 40 多个对象(这会导致 40 多个函数具有基本相同的代码,只是不同的对象和不同的值)。我想知道是否有办法在 Java 中制作这样的东西:
public void createObject(String objectName) {
getObject(objectName).setType(ymlFile.getString(objectName + ".type"));
// getObject(objectName) would be the object which has the same name as the value of the string objectName
}
目前我基本上必须为 40 多个对象提供这段代码(带有更多变量),所以我想知道是否可以通过使用名为 objectName 的字符串中的值来检索对象,这意味着我只需要调用该方法 40 次,而不是使用大块代码 40 次。
谢谢。
编辑: 不,这与 YAML 无关(无论如何也不是,只是显示一些代码)。我的主要问题是我需要能够使用字符串的值检索对象。
至于重复代码的例子,基本上是这样的:
public void createObject1() {
object1.setType(type1);
}
public void createObject2() {
object2.setType(type2);
}
// etc. for about 40 objects. basically i want to be able to change that to this:
public void createObject(String objectName) {
objectName.setType("value"); // so basically, retrieve the object that has the same name as the value of objectName
}
最佳答案
这看起来像 XY problem 的案例对我来说。
您可能只想使用两个数组来跟踪所有对象和类型,特别是因为命名变量 something1
是非常糟糕的做法。 , something2
等等。
所以替换你的 object
和type
变量:
YourClass[] objects = new YourClass[40];
Type types = new Type[40];
并替换您的creatObject()
方法为:
public void createObject(int index) {
objects[index].setType(types[index]);
}
你甚至可以像这样循环:
// This condition is overkill since both arrays should have the same size,
// but if you plan on doing something different than that, this should work.
for(int i = 0; i < objects.length && i < types.length; i++)
createObject(i);
如果你确实想使用字符串,你可以使用 Map<String, YourClass>
做同样的事情。和一个 Map<String, Type>
.
关于java - Java中如何使用字符串获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997035/