简体   繁体   中英

How to generate getters and setters in eclipse for mutable objects?

one of the sonar issue that I recently found was that "Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object"

For example ideally Eclipse should generate setter for date like following

public void setBillDate(Date billDate) {
    this.billDate = (Date)billDate.clone();
}

How can I force Eclipse to generate code like this?

Window -> Preferences -> Java -> Code Style -> Code Templates 

Enable project specific settings

You'll see "Setter Body", Edit:

${field} = ${param};

The code you need might be written as

try {
        ${field} = ${param}.getClass().cast( ${param}.clone() );
} catch( CloneNotSupportedException cnse ){
     // whatever
}

I admit that I don't know whether there is a template variable for the parameter class. Investigating...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM