gpt4 book ai didi

java - 为什么编译器在内部类中接受非最终变量?

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:35 26 4
gpt4 key购买 nike

我正在创建一个带有 seekbar 的 MediaPlayer。这里,mp 是一个 MediaPlayer 对象,seeker 是一个在 MainActivity 类中创建的 seekbar 对象。

我的理解是匿名内部类只能访问final成员,那么runnable是如何访问这些对象的(mp和seeker)

     h = new Handler();  // create a handler for the MainActivity

//create a runnable activity to change the progress of seekbar in MainThread for every 1 sec
Runnable r = new Runnable() {
@Override
public void run() {
if (mp != null) {
seeker.setProgress(mp.getCurrentPosition() / 1000);
}
h.postDelayed(this, 1000);
}
};

this.runOnUiThread(r);

注意:代码运行完美。感谢您的帮助。

最佳答案

它发生了,因为有一种叫做有效最终的东西。

jls-8.1.3:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

jls-4.12.4:

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

当变量只设置一次并在内部类中使用时,编译器将变量的修饰符变为final

考虑这段代码 Tests.java:

public class Tests  {
public static void main(String[] args) throws Throwable {
String value = "Hello";

Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(value);
}
};
}
}

上面的代码在编译时会产生下面的代码。看到编译器把 value 的修饰符改成 final 了吗?

Tests.class(已解码):

public class Tests {
public Tests() {
}

public static void main(String[] args) throws Throwable {
final String value = "Hello";
Runnable var10000 = new Runnable() {
public void run() {
System.out.println(value);
}
};
}
}

但是,如果你改变变量的值(见下面的代码),它不会被编译,因为编译器知道它不是一个有效的最终变量:

public class Tests  {
public static void main(String[] args) throws Throwable {
String value = "Hello";
value = "world";

Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(value);
}
};
}
}

关于java - 为什么编译器在内部类中接受非最终变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com