【发布时间】:2018-06-14 22:49:20
【问题描述】:
例如,我有一个字符串数组,在其中一个数组位置中,我有从 Coronel.getRep() 获得的字符串,我想知道是否有办法弄清楚它来自哪个类从,如果我可以从字符串中找出它是什么类,因为我有一个包含游戏 Stratego 中所有部分的包,我用 getRep() 函数中的字符串填充了游戏板,但是我该怎么做知道哪个棋子在某个位置的棋盘上,因为只有字符串我无法访问棋子的排名还是无论如何都可以这样做?
例如 getRespectiveClass("C") 它将返回类 Coronel。
public class Coronel {
private String nome;
private int total_pieces;
private int rank;
private String rep;
public Coronel() {
this.nome = "Coronel";
this.total_pieces = 2;
this.rank = 8;
this.rep = "C";
}
public String getRep() {
return this.rep;
}
public int getTotalPieces() {
return this.total_pieces;
}
public String toString() {
String a = this.rank + " / " + this.nome + " / " + this.total_pieces;
return a;
}
}
【问题讨论】:
-
如果您尝试将对象与字符串匹配,您可以使用某种类型的 Map,或者您可以遍历感兴趣对象的集合,例如 ArrayList,然后检查查看哪个对象在特定字段中保存感兴趣的字符串。此迭代可以通过 for 循环或流来完成,详细信息将取决于您如何收集感兴趣的对象。