在方法中处理不同的实例变量

handle different instance variables in method

所以如果我有一个方法,其中一个变量可以是一堆不同 classes 的实例,其中只有一些具有特定的实例变量,我如何在方法中使用这个实例变量没有收到 cannot be resolved or is not a field 错误?

考虑这段代码:

void method1(){
    SuperType randomInstance = getRandomInstance();
    if(randomInstance.stop == true) //do something
}

其中 SuperTyperandomInstance 可以容纳的所有可能实例的超级 class。

但是,实例不一定具有变量 stop,所以我收到一条错误消息 stop cannot be resolved or is not a field

所以我的问题是,有没有办法解决这个问题,或者我是否必须根据它们是否具有变量 stop 为不同的实例创建不同的方法?

给有问题的 classes 一个通用的超类型或接口(从你的代码来看,它们似乎有一个 - SuperType),并定义实例字段(它不是 "variable") 在超类型上或在接口上定义一个 getter 函数。 (实际上,即使超类型是 class,通常最好的做法是使用 getter 定义字段,即使您 可以 使它成为 publicprotected 实例字段。)

如果有一个stop 属性可以被看作是SuperType的一些子类共有的行为,你可以考虑定义一个接口——我们称它为 Stoppable - 具有方法 getStop(或者如果它是布尔值,则可能是 isStopped)和 setStop.

那么您的代码可以如下所示:

void method1(){
    SuperType randomInstance = getRandomInstance();
    if (randomInstance instanceof Stoppable) {
        Stoppable sInstance = (Stoppable) randomInstance;
        if(sInstance.getStop() == ...) //do something
    }
}

如果你不能通过引入一个接口来改变你的class层次结构(例如Stoppable)可以求助于反射来检测class是否有一个名为stop的provate字段.

您可以从 class here and Field is documented here

中找到字段 "listing" 的示例