在下面的代码中,我想知道为什么内联类中的 run() 能够访问外部类变量 - 信号量(即使它没有声明为final)。
private Semaphore semaphore = new Semaphore(bufferSize);
private Runnable producerRunnable = new Runnable(){
@Override
public void run()
{
try
{
semaphore.acquire();
}
catch(InterruptedException e)
{
System.out.println("producer was interrupted while trying to acquire semaphore");
}
}
};
我预计 Eclipse 会标记编译错误 - 因为信号量引用未声明为最终的
最佳答案
这是正常的。最终要求仅描述为适用于局部变量和参数( JLS ):
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final [...].
封闭实例的成员不需要最终才能访问它们。
关于java - 可运行内联类声明 - 能够访问外部非最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549452/