Util Method to get all attributes printed in System.out.println()

This small util override is to allow developers to view all instance variable values as a CSV format in Java. It is similar to the one seen as var_dump in PHP:

    @Override
    public String toString() {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder sbNote = new StringBuilder();
        sbNote.append("{");
        for (int i = 0; i < fields.length; i++) {
            try {
                sbNote.append(fields[i].getName() + " - " + fields[i].get(this)+", ");
            } catch (java.lang.IllegalAccessException e) {
                System.out.println(e);
            }
        }
        sbNote.append("}");
        return sbNote.toString();
    }

override the toString() method to the above code to get a comma separated description enclosed in {}

Another useful library is the Apache commons –

public String toString() {
       return ToStringBuilder.reflectionToString(this);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.