- Tricks on immutability
a. Always make a copy of mutable objects inside your methods, e.g.
b. How do I create an immutable Java Bean or POJO? Make it read-only, and pass any parameters during initialisation (in the constructor):
void myMethod(Date date) {
Date myCopy = new Date(date.getTime());
}
c. Immutable objects and Hibernate
public class MyClass {
private int param1;
private String param2;
private Date date;
public MyClass (int param1, String param2, Date d) {
this.param1 = param1;
this.param2 = param2;
this.date = new Date(d.getTime());
}
public int getParam1() {
return param1;
}
public String getParam2() {
return param2;
}
public Date getDate() {
return new Date(date.getTime());
}
}
- set the access type to “field” in order to use reflection to set the fields instead of property access, which uses setters.
- set mutable to false (Hibernate will perform small optimizations, too).
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου