toString() implementation

Most of the time, we hard code the field name in the toString method() of our model classes. So if we introduce a new variable or field, then again we need to do the change in the toString().

We can avoid this by using the java reflection.  For example,using reflection we can get the field name information as below.


 public String toString() {
        StringBuilder fieldInfo = new StringBuilder();
        try {
            fieldInfo.append(super.toString());
            Field[] fields = this.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fieldInfo.append(fields[i].getName()).append(" : ").append(fields[i].get(this)).append(" ");
            }

        } catch (IllegalAccessException ex) {
        }
        return fieldInfo.toString();
    }