Java 在 Eclipse 中自动生成 toString 方法的快捷方式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2653268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the shortcut to Auto-generating toString Method in Eclipse?
提问by Gordon
Is it good or bad practice auto-generating toString
methods for some simple classes?
toString
为一些简单的类自动生成方法是好是坏?
I was thinking of generating something like below where it takes the variable names and produces a toString
method that prints the name followed by its value.
我正在考虑生成类似下面的内容,它采用变量名称并生成一个toString
打印名称后跟其值的方法。
private String name;
private int age;
private double height;
public String toString(){
return String.format("Name: %s Age: %d Height %f", name, age, height);
}
采纳答案by Dónal
Eclipse 3.5.2 (and possibly earlier versions) already provides this feature. If you right-click within the editor, you'll find it under Source -> Generate toString()...
Eclipse 3.5.2(可能还有更早的版本)已经提供了这个特性。如果您在编辑器中右键单击,您将在 Source -> Generate toString()... 下找到它。
To answer your question about whether it's a bad practice to autogenerate toString()
, my opinion is that it is not. If the generated code is very similar to the code you would have written yourself, then why bother typing it out?
要回答您关于 autogenerate 是否是一种不好的做法的问题toString()
,我的观点是它不是。如果生成的代码与您自己编写的代码非常相似,那为什么还要打字呢?
回答by Steve
I personally like to implement a toString method for all objects, as it helps in debugging.
我个人喜欢为所有对象实现一个 toString 方法,因为它有助于调试。
I would look into using the Apache Commons ToStringBuilder.
我会考虑使用 Apache Commons ToStringBuilder。
You can implement a simple toString method using reflection as follows:
您可以使用反射实现一个简单的 toString 方法,如下所示:
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Using this method, you will not have to update your toString method if/when fields are added.
使用此方法,如果/何时添加字段,您将不必更新 toString 方法。
回答by leonbloy
To add to Steve's and Don's answers (+1 for them) :
添加到史蒂夫和唐的答案(他们+1):
Make your toString()
method simple, make sure it nevers triggers expections (especially be aware of fields that could be null).
使您的toString()
方法简单,确保它永远不会触发期望(尤其要注意可能为空的字段)。
If possible, don't call other methods of your class. At least, be sure that your toString()
method doesn't modify your object.
如果可能,不要调用类的其他方法。至少,请确保您的toString()
方法不会修改您的对象。
And be aware of silly exception-toString loops:
并注意愚蠢的异常 toString 循环:
public class MyClass {
...
public String toString() {
// BAD PRACTICE 1: this can throw NPE - just use field1
return " field1=" + field1.toString()
+ " extraData=" + getExtraData();
// BAD PRACTICE 2: potential exception-toString loop
}
public MyExtraData getExtraData() {
try {
.... do something
} catch(Exception e) {
throw new RuntimeException("error getting extradata - " + this.toString(),e);
}
}
}
回答by Will Iverson
Be clear when adding toString() as to the audience of the generated text. Some frameworks use the toString() method to generate end user visible text (e.g. certain web frameworks), whereas many people use toString() methods to generate debugging / developer information. Either way, make sure that you have enough uniqueness in the toString implementation to satisfy your requirements.
添加 toString() 时要清楚生成文本的受众。一些框架使用 toString() 方法生成最终用户可见的文本(例如某些 Web 框架),而许多人使用 toString() 方法生成调试/开发人员信息。无论哪种方式,请确保您在 toString 实现中具有足够的唯一性以满足您的要求。
The default JDK implementation of toString() generates developer info, so that's usually the pattern I recommend if possible, but if you are working on a project with a different idea / expectation you could wind up confused...
toString() 的默认 JDK 实现会生成开发人员信息,因此如果可能的话,这通常是我推荐的模式,但是如果您正在从事具有不同想法/期望的项目,您可能会感到困惑......
回答by Shervin Asgari
If you use lombokthey have a @ToStringannotation which will generate the toString for you.
如果您使用的龙目岛,他们有一个@ToString注释,这将产生的toString你。
The reason why this is much better to use instead of generating toString with eclipse for instance is that if you later add,remove or change attributes of the class, you will also have to regenerate the toString. If you use lombokyou don't have to do that.
例如,使用 eclipse 生成 toString 而不是使用它更好的原因是,如果您稍后添加、删除或更改类的属性,您还必须重新生成 toString。如果您使用lombok,则不必这样做。
回答by Deepak Gupta
Shortcut to generate toString() method
生成 toString() 方法的快捷方式
- Press Alt + Shift + S + S(double)
- Right click-> Source -> Generate toString() ...
- Go to Source menu-> Generate toString() ...
- Go to Windows menu-> Preferences -> General -> Keys (Write Generate toString on text field)
- 按Alt + Shift + S + S(双)
- 右键单击-> 源 -> 生成 toString() ...
- 转到源菜单-> 生成 toString() ...
- 转到Windows 菜单-> 首选项 -> 常规 -> 键(在文本字段上写入 Generate toString)
回答by Tomas Bisciak
Just noticed -In NetBeans IDEyou can generate toString() method by selecting fields you want to generate it for right click->insert code
or use shortcut ALT+INSERT
and then select toString().
刚刚注意到 -在 NetBeans IDE 中,您可以通过选择要为其生成的字段right click->insert code
或使用快捷方式ALT+INSERT
然后选择 toString()来生成 toString() 方法。
Way it looks is :
它的样子是:
@Override
public String toString() {
return "ClassName{"+"fieldName="+fieldName+'}';
}
Its great way to debug and no need for additional libs.
这是调试的好方法,不需要额外的库。
回答by Rajesh Goel
In IntelliJ Idea you can press alt+insert, the Generate popup will open; now select the fields and click the OK button; that's it.
在 IntelliJ Idea 中,您可以按 alt+insert,生成弹出窗口将打开;现在选择字段并单击确定按钮;就是这样。
Further tip: In the Generate toString dialog, it gives you a choice to select the template by clicking the drop down on the template combo box. Here you can select StringBuffer if you need to or any other template as required. Play with it to get accustomed. I like it :)
进一步提示:在 Generate toString 对话框中,您可以通过单击模板组合框上的下拉菜单来选择模板。如果需要,您可以在此处选择 StringBuffer 或根据需要选择任何其他模板。玩它以适应它。我喜欢 :)
回答by Ganesh Satpute
Considering some old answers including @Steve's, I'd like to add answer as per latest library.
考虑到包括@Steve 在内的一些旧答案,我想根据最新的库添加答案。
Add dependency
添加依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
In your class
在你的班级
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class User {
...
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
You can exclude certain fields as below
您可以排除某些字段,如下所示
...
@Override
public String toString() {
return ReflectionToStringBuilder.toStringExclude(this, "name"); // Name will be excluded from toString output
}