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 {
            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();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s