Beans
uPortal 3 has mange objects which follow the JavaBeans standards (private fields, like named getters & setters). These objects should all have the following 3 methods overridden: toString, hashCode, equals. The Jakarta Commons Lang library provides a utility for doing so in a standard way. All developers are encouraged to use the Commons Lang utilities for these tasks so all of the uPortal 3 objects have a standard behavior.
Bean.java
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.Date;
public class Bean {
private Sring name;
private Date birthday;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setBirthday(Date birthday) {
this.birthday= birthday;
}
public Date getBirthday() {
return this.birthday;
}
public void setAge(int age) {
this.age= age;
}
public int getAge() {
return this.age;
}
}
String toString()
Using Commons Lang to implement toString for the above Bean class
Bean.java
public String toString() {
return new ToStringBuilder(this)
.append("name", this.name)
.append("birthday", this.birthday)
.append("age", this.age)
.toString();
}
}
int hashCode()
Using Commons Lang to implement hashCode for the above Bean class
Bean.java
public int hashCode() {
//Binary or on each to ensure we get an odd number
final int classCode = this.getClass().hashCode() | 1;
final int classNameCode = this.getClass().getName().hashCode() | 1;
return new HashCodeBuilder(classCode, classNameCode)
.append(this.name)
.append(this.birthday)
.append(this.age)
.toHashCode();
}
}
boolean equals(Object)
Using Commons Lang to implement equals for the above Bean class
Bean.java
public boolean equals(Object obj) {
if (!(obj instanceof Bean)) {
return false;
}
if (this == obj) {
return true;
}
Bean other = (Bean)obj;
return new EqualsBuilder()
.append(this.name, other.name)
.append(this.birthday, other.birthday)
.append(this.age, other.age)
.isEquals();
}
}