It would be sometime challenging to print/log object properties when toString method is not overriden in class. We can use reflection to retrieve and print values but it would become tricky when object has other object refrences and so on.
Apache provides very good implementation (http://commons.apache.org/proper/commons-lang/download_lang.cgi) to solve the problem. I will try to explain this with simple example.
I have Employee Object having two properties employeeId(Numer) and department (Type Department), While Department object has two properties departmentName (String) and address (Type Address), while Address has three properties houseNumber, StreetName, and Pincode.
public class Employee {
private Number employeeId;
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Number getEmployId() {
return employeeId;
}
public void setEmployId(Number employId) {
this.employeeId = employId;
}
}
public class Department {
private String DepartmentName;
private Address address;
public String getDepartmentName() {
return DepartmentName;
}
public void setDepartmentName(String departmentName) {
DepartmentName = departmentName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
public class Address {
private Integer homeNumber;
private String streetName;
private Number pincode;
public Number getPincode() {
return pincode;
}
public void setPincode(Number pincode) {
this.pincode = pincode;
}
public Integer getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(Integer homeNumber) {
this.homeNumber = homeNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
}
Test Java class with main method:
import org.apache.commons.lang3.builder.RecursiveToStringStyle;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class RecursiveToStringDemo {
public static void main(String[] args) {
Address address = new Address();
address.setHomeNumber(23);
address.setStreetName("M.G. Road");
address.setPincode(395007);
Department department = new Department();
department.setDepartmentName("Human Resource");
department.setAddress(address);
Employee e = new Employee();
e.setEmployId(12);
e.setDepartment(department);
System.out.println("With Default ToString: "+ e.toString());
System.out.println("With Recursive To String "+ ReflectionToStringBuilder.toString(e,
new RecursiveToStringStyle()));
}
}
Output:
With Default ToString: in.softcaretech.Employee@3d44d0c6
With Recursive To String in.softcaretech.Employee@3d44d0c6[employeeId=12,department=in.softcaretech.Department@7de534cb[DepartmentName=Human Resource,address=in.softcaretech.Address@54fe0ce1[homeNumber=23,streetName=M.G. Road,pincode=395007]]]
Comments and suggestions are welcome.