In Java, a final field is generally considered a constant which can’t be modified once it is initialized. It’s partly true as most of the programmers know that reflection can break this rule. For example i have a class Person:
class Person {
private final String name;
Person(String name) { this.name = name; }
public String toString() { System.out.println(“name: ” + name); }
}And the code to test the “final” modification:
public static void main(String[] args) {
Person jacky = new Person("Jacky"); // initialize the name with constructor
Field nameField = Person.class.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(jacky, "Andy"); // try to modify the value here
System.out.println(jacky);
}The output is: name:
AndyNow what I’m able to modify the value of the final field, name. But if I initialize a value to the name during declaration:
class Person {
private final String name = “Jacky”;
public String toString() { System.out.println(“name: ” + name); }
}With this test:
public static void main(String[] args) {
Person jacky = new Person(); // default constructor
Field nameField = Person.class.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(jacky, "Andy"); // try to change the value here
System.out.println(jacky);
} The output is: name:
Jacky (the name field wasn’t changed)
Just want to share some funny points of Java with you.
PS: above code behaves differently with JDK 1.2, JDK 1.3, JDK 1.4 and JDK 5.