When you declare a variable *{_}final{_}*, you do not want anyone to change it. If the type of variable is *{_}primitive types{_}*, you can undoubtedly make it. Unfortunately, if the variable is a *{_}reference to an object{_}*, the "final" stuff you think may be not final\!
h2. Noncompliant Code Example
class Test{
Test(int a, int b)
{ Â Â this.a = a; Â Â this.b = b; Â }
 void set_ab(int a, int b){  this.a = a;  this.b = b; }
}
void print_ab()
{ Â Â System.out.println("the value a is: "+this.a); Â Â System.out.println("the value b is: "+this.b); Â }
private int a;
private int b;
}
public class TestFinal1 {
public static void main(String\[\] args)
{ Â Â Â Â Â Â Â final Test mytest = new Test(1,2); Â Â Â Â Â Â Â mytest.print_ab(); Â Â Â Â Â Â Â //now we change the value of a,b. Â Â Â Â Â Â Â mytest.set_ab(5, 6); Â Â Â Â Â Â Â mytest.print_ab(); Â Â Â Â Â Â Â Â Â Â }
We can see that the value of a and b has been changed, which means that when you declare a reference *{_}final{_}*, it only means that the reference can not be changed but the contents it refer to can still be changed\!
\\
h2. Compliant Solution
If you do not want to change a and b after they are initialized, the simplest approach is to declare a and b *{_}final:_* private final int a;
private final int b;
But now you can not have setter method of a and b.
h2. Compliant Solution 2
An alternative approach is to provide the *{_}clone{_}* method in the class. When you want do something about the object, you can use *{_}clone{_}* method to get a copy of original object. Now, you can do everything to this new object, and the original one will be never changed. public Test2 clone() throws CloneNotSupportedException
{ Â Â Test2 cloned = (Test2) super.clone(); Â Â return cloned; Â }\\
h2. Risk Assessment
Using final to declare the reference to an object is a potential security risk, because the contents of the object can still be changed.
|| Recommendation || Severity || Likelihood || Remediation Cost || Priority || Level ||
| SEC37-J | medium | likely | low | {color:red}{*}P18{*}{color} | {color:red}{*}L1{*}{color} |
h2. Automated Detection
TODO
h2. Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
h2. References
Chapter 6, Core Java⢠2 Volume I - Fundamentals, Seventh Edition |