【问题标题】:How to get the class type from a string如何从字符串中获取类类型
【发布时间】: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 循环或流来完成,详细信息将取决于您如何收集感兴趣的对象。

标签: java oop


【解决方案1】:

这个问题的直接答案是否定的。 Coronel & String (rep) 共享Aggregation 关系,因此您确实无法从其属性之一检索容器类信息。

满足您要求的最佳解决方案是使用 Coronel 的 Array of Object,而不是存储 Rep 的 Array of Strings。您可以覆盖toString() 方法以返回Rep 属性。因此,您对数组的表示没有改变,但是内部结构是可以的。当您可以访问 Coronel 对象时,您可以检索任何您想要的属性,例如等级、名称等。

【讨论】:

    猜你喜欢
    • 2014-01-01
    • 2011-01-25
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多