[java] how to convert object to string in java

/**  * This toString-Method works for every Class, where you want to display all the fields and its values  */ public String toString() {

StringBuffer sb = new StringBuffer();

Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones

for (Field field : fields){

    try {

        field.setAccessible(true);
        String key=field.getName();
        String value;

        try{
            value = (String) field.get(this);
        } catch (ClassCastException e){
            value="";
        }

        sb.append(key).append(": ").append(value).append("\n");

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

return sb.toString(); }