"this" w/in Runnable 无法识别实例变量

instance variables not recognized with "this" w/in Runnable

我在尝试引用可运行对象中 class 的实例变量时遇到了一个奇怪的问题。这是我的(简化的)代码:

public class Hello{

    private Boolean truth;

    public Hello(Boolean truthParam){

        this.truth = true;

        Runnable myRunnable = new Runnable(){
            public void run(){
                if (this.truth){
                    System.out.println("i declare the truth!");
                }else{
                    System.out.println("come back tomorrow");
                }

            }
       };
    }
}

当我编译这段代码时,我得到了"error: cannot find symbol ... symbol: variable truth"

我想也许在 Runnable 的上下文中,"this" 不再是主要的 class 对象;但是,我将 "this" 打印到控制台,它是 Hello 的一个实例。这引出了一个问题:为什么我无法通过它访问我的实例变量?

然后我从 if (this.truth) 中删除了 "this",将其转换为 if (truth);不用说了,这个编译和运行。我对这种我无法解释的行为感到很困惑。也许我只是误解了 "this"...

的复杂性

首先:

您正在分配 this.truth = true。但是你从未声明 [​​=12=].

如果你想把它作为你的class的一个字段,你需要创建一个字段private boolean truth,或者如果你只是想在本地使用它,则在你的构造函数中使用final boolean truth = true(尽管那将是毫无意义的)。


关于this关键字的用法:

this 总是引用你调用的方法所在的对象。

在您的行 if(this.truth) { 中,您位于 Runnable 类型对象的方法 run 中。所以 this 指的是 Runnable 类型的确切对象,它没有名称 truth 的字段。因此 this.truth 会抛出一个错误。

您可以简单地使用 truth 或使用 Hello.this.truth

如果您自己在 class 中有一个字段 truth 但想访问 class Hello 中的字段,则第二个将最有用。

所以,想象一个简单的用例:

public class A
{
    private boolean field = false;

    public void foo()
    {
        Runnable r = new Runnable()
        {
            private boolean field = true;

            @Override
            public void run()
            {
                System.out.println(field); // prints true
                System.out.println(this.field); // prints true
                System.out.println(A.this.field); // prints false
            }
        };
    }
}

在您的代码中,this 引用 Runnable class 的对象。 您真正想要的是 Hello class 的对象。 如果您在两个 class 中,this 关键字将引用内部的一个。 引用外部的一种方法是编写 Class.this 这种情况下需要改成(也是字段名的小错误)

public class Hello{

private Boolean truth;

public Hello(Boolean truthParam){

    this.truth = true;

    Runnable myRunnable = new Runnable(){
        public void run(){
            if (Hello.this.truth){
                System.out.println("i declare the truth!");
            }else{
                System.out.println("come back tomorrow");
            }

        }
   };
}

}