toString 实现的最佳标准样式是什么?

发布于 2024-09-27 12:58:24 字数 1431 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

暗喜 2024-10-04 12:58:24

我认为 GuavaMoreObjects.toStringHelper() 非常好,但主要是最好使用一些一致的格式:

public String toString() {
  return Objects.toStringHelper(this)
      .add("prop1", prop1)
      .add("prop2", prop2)
      .toString();
}

// Produces "SimpleClassName{prop1=foo, prop2=bar}"

I think the format produced by Guava's MoreObjects.toStringHelper() is pretty nice, but it's mainly just good to have some consistent format that you use:

public String toString() {
  return Objects.toStringHelper(this)
      .add("prop1", prop1)
      .add("prop2", prop2)
      .toString();
}

// Produces "SimpleClassName{prop1=foo, prop2=bar}"
幽梦紫曦~ 2024-10-04 12:58:24

就我个人而言,我发现 []{} 的混合不太容易立即查看层次结构。

我喜欢这种格式(并且我已经在很多地方看到过它的使用):

SimpleClassName[prop1=value, prop2=value]
SimpleClassName[prop1=value, prop2=NestedObject[prop3=value]]

还可以使用 @ 添加标识符,例如 < 的默认样式 a href="http://commons.apache.org/lang/" rel="nofollow noreferrer">commons-lang ToStringBuilder 这样做(使用它自己的示例):

Person@182f0db[name=John Doe,age=33,smoker=false]

Personally, I find the mix of [] and {} not so easy to get an immediate view of the hierarchy.

I like this format (and I've seen it being used in a number of places):

SimpleClassName[prop1=value, prop2=value]
SimpleClassName[prop1=value, prop2=NestedObject[prop3=value]]

There's also the possibility to add an identifier with @, for example the default style for the commons-lang ToStringBuilder does that (using its own example):

Person@182f0db[name=John Doe,age=33,smoker=false]
内心旳酸楚 2024-10-04 12:58:24

json 语法似乎非常适合,因为它是专门为将复杂对象表示为字符串而设计的

Person = {
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": 
    {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": 
    [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

json syntax seems to fit pretty well since it was designed specifically to represent complex objects as strings

Person = {
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": 
    {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": 
    [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}
戏舞 2024-10-04 12:58:24

不是问题的直接答案,但是以下内容可以在初始开发过程中节省时间:

免责声明:使用 Apache Commons 库。

  1. Java > 中添加一个名为 xreflect 的新 Eclipse 模板。编辑>模板;将以下内容添加到其模式文本区域中:
// ---------- template start ----------- //
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder,org.apache.commons.lang.builder.ReflectionToStringBuilder)}
/*
 * (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(
        final Object pObj) {
    return EqualsBuilder.reflectionEquals(this, pObj);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return ReflectionToStringBuilder.toString(this);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}
// ---------- template end ----------- //
  1. 给出OKOK
  2. 只需转到Java类的末尾,输入xreflect 并按 Ctrl + Space 自动填充 equals()、toString() 和 hashCode() 方法。

Not a direct answer to the question, however below would be a time saver during initial development:

Disclaimer: Apache Commons library is used.

  1. Add a new Eclipse template called xreflect in Java > Editor > Templates; Add below into its pattern textarea:
// ---------- template start ----------- //
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder,org.apache.commons.lang.builder.ReflectionToStringBuilder)}
/*
 * (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(
        final Object pObj) {
    return EqualsBuilder.reflectionEquals(this, pObj);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return ReflectionToStringBuilder.toString(this);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}
// ---------- template end ----------- //
  1. Give OK, OK
  2. Just go to the end of a Java class, type xreflect and press Ctrl + Space to autofill equals(), toString() and hashCode() methods automatically.
怎樣才叫好 2024-10-04 12:58:24

是否有任何标准,或者只是某种风格的最佳实践?

不会。toString() 方法的“最佳”输出取决于您想要使用它的用途。是为了以允许反序列化的形式序列化对象状态吗?它是用于创建调试消息吗?是为了渲染对象以显示给最终用户吗?

(请注意,在 Java 中,toString() 方法可用于任一目的。在最终用户消息中使用 toString() for / 会出现问题...但是人们无论如何都要做。)

如果您想为调试/日志记录 toString() 方法开发内部样式,那没问题。但除非有这样的要求,否则我不会打扰。在我看来,这种努力最好用在其他地方。

Is there any standard, or simply just a best practice for a style?

No. The "best" output for a toString() method is determined by what you want to use it for. Is it for serializing the object state in a form that allows it to be deserialized? Is it for creating debug messages? Is it for rendering the object for display to end-users?

(Note that in Java, the toString() method can be used for either purpose. Using toString() for / in end-user messages has problems ... but people do it anyway.)

If you want to develop an in-house style for your debug/logging toString() methods, that's fine. But unless there was a requirement for this, I wouldn't bother. IMO, it is effort that could better be spent elsewhere.

爱人如己 2024-10-04 12:58:24

如果您的对象具有可能用作标识符的内容,我会实现类似于您的第二个示例的内容:

[SimpleClassName:id] { prop1:value, prop2:[NestedObject:id] { prop3:value }}

其中 id 是对该对象作为标识符有意义的任何内容 - 规范的名称Person 对象、数据库中对象的主键等。

If your objects have something that might be useful as an identifier, I'd implement something like your second example:

[SimpleClassName:id] { prop1:value, prop2:[NestedObject:id] { prop3:value }}

Where the id is whatever makes sense for that object to be an identifier - the name for the canonical Person object, a primary key for an object from a database, etc.

森林迷了鹿 2024-10-04 12:58:24

既然您询问了其他开源项目,那么 jEdit 是如何实现的,这与 Wouter 的类似:

BufferChanging[what=BUFFER_CHANGING,source=org.gjt.sp.jedit.EditPane[active,global]]

Since you asked about what other open source projects to, here's how jEdit does it, which is similar to Wouter's:

BufferChanging[what=BUFFER_CHANGING,source=org.gjt.sp.jedit.EditPane[active,global]]
陪你到最终 2024-10-04 12:58:24

查看 phps print_r($obj, true)
或者serialize()也可以工作,但不知道它到底需要什么。
jsons 也是一个干净的解决方案,特别是如果你想在 javascript 环境中导入数据

check out phps print_r($obj, true)
or also serialize() could work, dont know exactly for what its needed for.
jsons is also a clean solution, especially if u want to import the data in javascript environbments

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文