【发布时间】:2019-07-22 17:49:48
【问题描述】:
我有一个小班,里面有一些数据,叫做MyData:
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
....
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
}
然后我有一个包含此类数组的类,用于特定类型的人,称为AllMyData:
public class AllMyData {
public ArrayList<MyData> cli = new ArrayList<>();
public ArrayList<MyData> sub = new ArrayList<>();
public ArrayList<MyData> emp = new ArrayList<>();
public ArrayList<MyData> exp = new ArrayList<>();
public ArrayList<MyData> oex = new ArrayList<>();
public ArrayList<MyData> bin = new ArrayList<>();
public ArrayList<MyData> ven = new ArrayList<>();
....
}
在主类中,我需要将新项目添加到特定数组(如果id 不存在),其中我有一个代表AllMyData 数组的字符串
public AllMyData elems = new AllMyData();
public void initArray(int id, String name, String tip) {
//this is an example just for "cli" element and "cli" is in String tip
if (!checkForId(elems.cli, id)) {
MyData element = new MyData(name, name, id);
elems.cli.add(element);
}
}
private boolean checkForId(ArrayList<MyData> a, int id) {
for (MyData e : a) {
if (e.id == id) return true;
}
return false;
}
那我只需要一个电话,例如:
initArray(5, "Test", "emp");
并希望避免使用 switch 语句并为每种类型重复代码。在此调用中,“emp”将是元素 elems.emp
有没有办法使用字符串名称访问elems 成员而不是创建 switch 语句?
【问题讨论】:
-
这听起来真的像 XY 问题。
-
我建议您按照命名约定编写代码。就目前而言,当变量名以大写字母开头而类名以小写字母开头时,阅读代码会非常混乱。
-
@Gendarme 我继续把类名大写,因为它很难看。
-
对不起,Java 还是新手...
-
解释什么是 XY 问题:asking how to implement a solution to a problem you had, rather than asking about how to properly solve that problem。在这种情况下,您展示了一种非常奇怪的方式来做事:如果您有不同类型的数据,请创建一个对所有共享功能进行编码的“主类”,并将其扩展到特定类捕获您的不同数据类型,每种数据类型一个。然后你依靠 java 的强类型来根据类型匹配调用正确的方法。
标签: java class arraylist class-members