【问题标题】:How Can I Tell Which Inherited Class This Belongs To?我怎么知道它属于哪个继承类?
【发布时间】:2017-09-17 20:08:33
【问题描述】:

我正在处理从一个名为 Creature 的类继承的多个类。我有一个 Creature 对象数组,我正在循环这些对象以确定数组中的哪些是子类 Animal。我试过instanceOf,但我收到一个错误,说我将它声明为一个变量。这是我的方法的样子:

 public void notifyStateChange() {
        for (int i = 0; i < count; i++) {
            Class c = creatures[i].getClass();
            if (c.getName().equals("Animal")) {
                System.out.println("Animal type here");
            }
        }
    }

【问题讨论】:

  • 语法是if (creatures[i] instanceof Animal)
  • 但是如果你的代码需要这样的东西,这表明它可能设计得更好,因为instanceof 的大量使用是一种“反模式”,一种暗示代码损坏的设计。跨度>
  • 使用 instanceOf 我得到错误...这里不允许变量声明;不兼容的类型:无法将生物转换为布尔值
  • 只覆盖继承类中的方法,并从引用中调用方法
  • 这里有点不对劲。发布您的代码并尝试使用instanceof

标签: java inheritance subclass


【解决方案1】:

您不必检索数组中对象的运行时类来确定对象是否为Animal 类型。正确使用instanceof即可:

 public void notifyStateChange() {
        for (int i = 0; i < count; i++) {
            if (creatures[i] instanceof Animal) {
                System.out.println("Animal type here");
            }
        }
    }

或者,您可以尝试以下方法。它接近你正在尝试的东西。只需使用getSimpleName 而不是getName

public void notifyStateChange() {
    for (int i = 0; i < count; i++) {
        Class c = creatures[i].getClass();
        if (c.getSimpleName().equals("Animal")) {
            System.out.println("Animal type here");
        }
    }
}

【讨论】:

  • instanceOf 不起作用,但我认为这可能与我没有在包内构建的事实有关,但您的替代解决方案就像一个魅力!谢谢。
  • 当两个类具有相同的名称 Animal 和不同的包时,它会刹车。这实际上不是一个好方法。
【解决方案2】:

我认为最好的方法是将操作放入 Animal 类本身或使用包装器以防万一。我给你和想法,因为有很多方法可以实现它。 您的代码应如下所示:

public void notifyStateChange() {
    for (int i = 0; i < count; i++) {
        creatures[i].doSmth();
    }
}

作为替代方案,您可以将所有doSmth() 放入EnumMap 中,然后在代码之前的某处选择正确的实例。 if..else 的主要问题是如果你添加Creature 的新孩子,那么你必须修改所有这些地方。

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多