How to use the toString method in Java?

前端 未结 13 1195
说谎
说谎 2020-11-21 06:26

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

13条回答
  •  执笔经年
    2020-11-21 06:55

    /**
     * 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();
    }
    

提交回复
热议问题