java - 如何在Java中使用字符串获取对象
问题描述
我一直在努力让我的代码更高效,但我遇到了一个问题,我必须重复自己很多次才能创建 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 问题的一个案例。
您可能只想使用两个数组来跟踪所有对象和类型,特别是因为命名变量等是非常糟糕的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>
如果你真的想使用字符串,你可以用 a和 a做同样的事情Map<String, Type>
。
推荐阅读
- python - 我在 python 中编写了一个代码来创建一个带有卷号、名称和标记的二进制文件。在输入卷号时,它应该更新标记
- java - 了解应用程序上下文
- firebase - Google App Engine 在不同项目中访问 Firebase
- prometheus-alertmanager - alertmanager 不会发送电子邮件
- selenium-webdriver - 无法用硒识别输入元素
- wordpress - htaccess https www。尾随斜线
- javascript - 数据库中的 UTC 日期时间,并且不从控制器执行时区转换,仅在客户端浏览器中处理转换
- flutter - 从二维码检测中获取信息
- python - EC2 的 SageMaker 估算器
- javascript - 如何在 javascript 上查看日期和时间?