public class UpdateFinalField {
final int f;
final Runnable updater;
UpdateFinalField() {
updater = () -> { f = 1; };
f = 0;
}
public static void main(String[] args) {
UpdateFinalField u = new UpdateFinalField();
System.out.println("u.f = " + u.f);
u.updater.run();
System.out.println("u.f = " + u.f);
}
}
$ jdk.8u131/bin/javac -d classes.8 UpdateFinalField
$ jdk.8u131/bin/java -cp classes.8 UpdateFinalField
u.f = 0
u.f = 1
$ jdk.9/bin/java -cp classes.8 UpdateFinalField
u.f = 0
u.f = 1
$ jdk.9/bin/javac -d classes.9 UpdateFinalField
$ jdk.9/bin/java -cp classes.9 UpdateFinalField
u.f = 0
Exception in thread "main" java.lang.IllegalAccessError: Update to non-static final field UpdateFinalField.f attempted from a different method (lambda$new$0) than the initializer method <init>
at UpdateFinalField.lambda$new$0(UpdateFinalField.java:6)
at UpdateFinalField.main(UpdateFinalField.java:13)
final int f;
final Runnable updater;
UpdateFinalField() {
updater = () -> { f = 1; };
f = 0;
}
public static void main(String[] args) {
UpdateFinalField u = new UpdateFinalField();
System.out.println("u.f = " + u.f);
u.updater.run();
System.out.println("u.f = " + u.f);
}
}
$ jdk.8u131/bin/javac -d classes.8 UpdateFinalField
$ jdk.8u131/bin/java -cp classes.8 UpdateFinalField
u.f = 0
u.f = 1
$ jdk.9/bin/java -cp classes.8 UpdateFinalField
u.f = 0
u.f = 1
$ jdk.9/bin/javac -d classes.9 UpdateFinalField
$ jdk.9/bin/java -cp classes.9 UpdateFinalField
u.f = 0
Exception in thread "main" java.lang.IllegalAccessError: Update to non-static final field UpdateFinalField.f attempted from a different method (lambda$new$0) than the initializer method <init>
at UpdateFinalField.lambda$new$0(UpdateFinalField.java:6)
at UpdateFinalField.main(UpdateFinalField.java:13)
- duplicates
-
JDK-8043179 Lambda expression can mutate final field
- Resolved