如何在不使用 instanceOf 或 getClass() 的情况下知道 class 类型?

How to know the class type without using instanceOf or getClass()?

我有一个由 Student 和 Employee 继承的 class Person。 我有另一个 class PersonList,它有一个 Person 类型的列表,即 List(元素可以是 Student 和 Employee 类型)

有一个第三方 API,它有两个重载方法,即

void display(Employee emp)void display (Student student)

当我遍历 Person 列表时,我需要知道对象类型,以便我可以调用适当的 display() 方法。

我不想使用 instanceOf 或 getClass()。

总的来说,本案例中的第三方API设计的很糟糕。特别是如果您被允许更改它依赖的 classes...

但是无论如何,如果你被允许改变 classes,你可以添加一个像 displayMe 这样的方法(我假设你的第三方 class 被称为 PersonPrinter).

abstract class Person {
    abstract public void displayMe();
}

class Employee extends Person {
    public void displayMe() {
        PersonPrinter.display(this);
    }
}

class Student extends Person {
    public void displayMe() {
        PersonPrinter.display(this);
    }
}

因为每个 classes 都知道它是什么,所以它会从 PersonPrinter 中选择 display 的正确版本。

现在你可以这样写循环了:

    List<Person> personList = new ArrayList<>();
    personList.add(new Employee());
    personList.add(new Student());
    for ( Person p : personList ) {
        p.displayMe();
    }