我如何判断这属于哪个继承 Class?

How Can I Tell Which Inherited Class This Belongs To?

我正在使用多个 class 继承自 class 的 Creature。我有一个 Creature 对象数组,我正在遍历这些对象以确定数组中的哪些是 subclass 动物。我试过 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");
            }
        }
    }

您不必检索数组中对象的 运行 时间 class 来确定对象是否属于 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");
        }
    }
}

我认为最好的方法是对 Animal class 本身采取行动,或者在不可能的情况下使用包装器。我给你和想法,因为有很多方法可以实现它。 您的代码应如下所示:

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

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