Can not resolve "May expose internal representation by returning reference to mutable object"

Viewed 3840

SonarQube keeps reporting an issue for rule "may expose internal representation by returning reference to mutable object".

I fixed it based on a guide of the Carnegie Mellon University, but SonarQube still raises this issue:

public Date getDatime(){
    return (Date)this.datime.clone();//IJTI-316
    // .getDatime() may expose internal representation by returning *.datime
}

How can I resolve / avoid this issue?

1 Answers

The clone operation does a shallow copy, meaning that most of the Date's instance variables are shared between both instances. To fully solve the error you need to make an entirely new object in the regular sense.

Maybe:

return new Date(this.datime.getTime());
Related