Skip to content

Commit 66aa1b3

Browse files
committed
feat: add Java 26 final field mutation demo with JEP 500 notes
Signed-off-by: https://github.com/Someshdiwan <someshdiwan369@gmail.com>
1 parent f77f341 commit 66aa1b3

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import java.lang.reflect.Field;
2+
3+
public class FinalFieldDemo {
4+
5+
public static void main(String[] args) {
6+
7+
try {
8+
User user = new User("Somesh");
9+
10+
System.out.println("Before reflection: " + user.name);
11+
12+
Field field = User.class.getDeclaredField("name");
13+
field.setAccessible(true); // deep reflection
14+
field.set(user, "Changed Name"); // JDK 26 warns by default
15+
16+
System.out.println("After reflection: " + user.name);
17+
18+
} catch (Exception e) {
19+
e.printStackTrace();
20+
}
21+
}
22+
}
23+
24+
class User {
25+
final String name;
26+
27+
User(String name) {
28+
this.name = name;
29+
}
30+
}
31+
32+
/*
33+
What changed: Previous vs New
34+
35+
Previous Java style:
36+
- final fields could still be changed using deep reflection
37+
- setAccessible(true) + Field.set(...) could bypass immutability
38+
- final was not fully enforced at runtime
39+
40+
New Java 26 style:
41+
- JDK 26 warns when code mutates final fields through deep reflection
42+
- This prepares for a future release where such mutation will be denied by default
43+
- Goal: make final actually mean final
44+
45+
Why the new approach is better:
46+
- Better integrity
47+
- Better security
48+
- More reliable immutability
49+
- Allows stronger JVM optimizations
50+
51+
Pros:
52+
1. Safer code
53+
- Prevents unexpected mutation of final fields
54+
55+
2. Better reliability
56+
- final fields behave more like developers expect
57+
58+
3. Better JVM optimization potential
59+
- Immutable fields are easier to optimize
60+
61+
4. Stronger platform integrity
62+
- Reflection loophole is being closed
63+
64+
Cons:
65+
1. Legacy libraries may warn
66+
- Old frameworks using reflection may need updates
67+
68+
2. Migration effort
69+
- Some tools depend on final-field mutation
70+
71+
3. Behavior change over time
72+
- Warning now, stricter denial later
73+
74+
Best use case:
75+
- Understanding JEP 500
76+
- Learning why reflection-based mutation is discouraged
77+
- Testing migration impact in older codebases
78+
79+
Compile and run:
80+
javac FinalFieldDemo.java
81+
java FinalFieldDemo
82+
83+
Helpful testing options in JDK 26:
84+
java --illegal-final-field-mutation=warn FinalFieldDemo
85+
java --illegal-final-field-mutation=debug FinalFieldDemo
86+
java --illegal-final-field-mutation=deny FinalFieldDemo
87+
java --enable-final-field-mutation=ALL-UNNAMED FinalFieldDemo
88+
*/

0 commit comments

Comments
 (0)