使用谷歌番石榴的Objects.ToStringHelper [英] Using Google Guava's Objects.ToStringHelper
问题描述
我在commons-lang中使用了ToStringBuilder.reflectionToString(class)
来为简单的DTO实现toString()
.现在,我正在尝试使用Google Guava代替Apache commons库.我在番石榴中找到了Objects.ToStringHelper
.但是如果班上有很多成员,这太冗长了.例如:
I used ToStringBuilder.reflectionToString(class)
in commons-lang, to implement toString()
for simple DTOs. Now I'm trying to use Google Guava instead of Apache commons library. And I found Objects.ToStringHelper
in Guava. But it's too verbose if there're lots of members in the class. For example:
@Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass()).add("name", name)
.add("emailAddress", emailAddress)
.add("department", department).add("yearJoined", yearJoined)
.toString();
}
如果我使用commons-lang,
要简单得多.
is much simpler if I use commons-lang:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
是否有更好的方法来用Guava而不是commons-lang来实现toString()
?
Is there any better ways to implement toString()
with Guava, not with commons-lang?
推荐答案
我对番石榴的com.google.common.base.MoreObjects.toStringHelper()
有一些窍门.我将 IntelliJ IDEA 配置为在自动生成toString()
方法时使用它.我假设您可以在 Eclipse 中执行相同的操作.这是在 Intellij 中完成的方法:
I have a little trick for Guava's com.google.common.base.MoreObjects.toStringHelper()
. I configured IntelliJ IDEA to use it when auto-generating toString()
methods. I assume you can do the same in Eclipse. Here's how to do it in Intellij:
- 走进课堂
- 点击 Alt + 插入弹出生成"菜单
- 选择
toString()
- 点击设置"按钮
- 转到模板"标签
- 创建一个名为"Guava's MoreObjects.toStringHelper()"的新模板(我通过复制"ToStringBuilder"模板来做到这一点)
-
将模板更改为:
- go inside a class
- hit Alt + Insert to popup the "Generate" menu
- choose
toString()
- click the "Settings" button
- go to the "Templates" tab
- create a new template named "Guava's MoreObjects.toStringHelper()" (I did it by copying the "ToStringBuilder" template)
change the template to:
public String toString() {
#set ($autoImportPackages = "com.google.common.base.MoreObjects")
return MoreObjects.toStringHelper(this)
#foreach ($member in $members)
.add("$member.name", $member.accessor)
#end
.toString();
}
保存模板,关闭设置"和生成toString()"窗口
save the template, close the "Settings" and "Generate toString()" windows
在类中添加新字段时,只需重新生成toString()
方法(IDEA会要求您确认要替换现有的toString()
方法).
When you add a new field to the class, simply re-generate the toString()
method (IDEA will ask you to confirm that you want to replace the existing toString()
method).
这篇关于使用谷歌番石榴的Objects.ToStringHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!