为什么在DTO中覆盖toString方法 [英] Why to override toString Method inside DTO

查看:519
本文介绍了为什么在DTO中覆盖toString方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到DTO对象中的大部分时间,
toString方法被动作覆盖。

I see that Most of the times in the DTO object , the toString Method is actaully overridden .

例如:

public class Person implements Serializable {

    private String firstName;
    private String lastName;
    private int age;

    /**
     * Creates a new instance of Person
     */
    public Person() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //Overriding toString to be able to print out the object in a readable way
    //when it is later read from the file.
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append(firstName);
        buffer.append("\n");
        buffer.append(lastName);
        buffer.append("\n");
        buffer.append(age);
        buffer.append("\n");

        return buffer.toString();
    }


}

请问有人吗?告诉我这样做有什么用?

Could anybody please tell me what is the use of doing so ??

推荐答案

答案在你的代码评论中。调试时,您希望能够打印对象的可读表示形式。如果你不覆盖 toString ,你很可能会有如下表示:

The answer is in your code comment. When debugging, you want to be able to print a human readable representation of your object. If you don't override toString you will most likely have a representation like:

Person@129cfbb

这篇关于为什么在DTO中覆盖toString方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆