Java 26 Final Keyword Truly Means Final

Java finally made a 𝗳𝗶𝗻𝗮𝗹 keyword mean 𝗙𝗶𝗻𝗮𝗹 and everyone is talking about it... Previously, the final keyword in Java indicated that a variable's value cannot be changed once initialized. However, through the use of the deep reflection 𝘀𝗲𝘁𝗔𝗰𝗰𝗲𝘀𝘀𝗶𝗯𝗹𝗲 and 𝘀𝗲𝘁 methods of the 𝗷𝗮𝘃𝗮.𝗹𝗮𝗻𝗴.𝗿𝗲𝗳𝗹𝗲𝗰𝘁.𝗙𝗶𝗲𝗹𝗱 class, it was possible to override this behavior. Consider the following example: ``` // A normal class with a final field class C {   final int x;   C() { x = 100; } } // 1. Perform a deep reflection over the final field in C java.lang.reflect.Field f = C.class.getDeclaredField("x"); f.setAccessible(true);   // Make C's final field mutable // 2. Create an instance of C C obj = new C(); System.out.println(obj.x); // Prints 100 // 3. Mutate the final field in the object f.set(obj, 200); System.out.println(obj.x); // Prints 200 f.set(obj, 300); System.out.println(obj.x); // Prints 300 ``` However, with the upcoming Java 26 release, the final keyword will truly mean final. This change is one of the intriguing updates in Java 26, and I look forward to discussing more of the new features. For further details, check out the official JEP: https://lnkd.in/gsKzzr6R #java

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories