What is the best standard style for a toString imp

2019-01-22 06:30发布

We have a lot of objects for which we like to implement a simple toString to output attributes of the object. Some of these attributes may be complex objects themselves.

Is there any standard, or simply just a best practice for a style? I'm thinking something like:

[SimpleClassName] { prop1:value, prop2:value }

In which case a nested value would look like:

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

We are using Java but I find myself asking the same question in most languages!

8条回答
等我变得足够好
2楼-- · 2019-01-22 07:01

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]]
查看更多
混吃等死
3楼-- · 2019-01-22 07:03

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}"
查看更多
登录 后发表回答