简体   繁体   English

在 Eclipse 中自动生成 toString 方法的快捷方式是什么?

[英]What are the shortcut to Auto-generating toString Method in Eclipse?

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);
}

Eclipse 3.5.2 (and possibly earlier versions) already provides this feature. Eclipse 3.5.2(可能还有更早的版本)已经提供了这个特性。 If you right-click within the editor, you'll find it under Source -> Generate toString()...如果您在编辑器中右键单击,您将在 Source -> Generate toString()... 下找到它。

To answer your question about whether it's a bad practice to autogenerate toString() , my opinion is that it is not.要回答您关于自动生成toString()是否是一种不好的做法的问题,我的观点是它不是。 If the generated code is very similar to the code you would have written yourself, then why bother typing it out?如果生成的代码与您自己编写的代码非常相似,那为什么还要打字呢?

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 方法。

If you use lombok they have a @ToString annotation 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.例如,使用 eclipse 生成 toString 而不是使用它更好的原因是,如果您稍后添加、删除或更改类的属性,您还必须重新生成 toString。 If you use lombok you don't have to do that.如果您使用lombok ,则不必这样做。

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);
           }

       }

}

In IntelliJ Idea you can press alt+insert, the Generate popup will open;在 IntelliJ Idea 中,您可以按 alt+insert,将打开 Generate 弹出窗口; now select the fields and click the OK button;现在选择字段并单击确定按钮; that's it.就是这样。

按 alt + 插入生成弹出窗口

选择字段并保持默认模板不变

生成到字符串函数

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.进一步提示:在 Generate toString 对话框中,您可以通过单击模板组合框上的下拉菜单来选择模板。 Here you can select StringBuffer if you need to or any other template as required.如果需要,您可以在此处选择 StringBuffer 或根据需要选择任何其他模板。 Play with it to get accustomed.玩它以适应它。 I like it :)我喜欢 :)


Shortcut to generate toString() method生成 toString() 方法的快捷方式


  1. Press Alt + Shift + S + S (double)Alt + Shift + S + S (双)
  2. Right click -> Source -> Generate toString() ...右键单击-> 源 -> 生成 toString() ...
  3. Go to Source menu -> Generate toString() ...转到源菜单-> 生成 toString() ...
  4. Go to Windows menu -> Preferences -> General -> Keys (Write Generate toString on text field)转到Windows 菜单-> 首选项 -> 常规 -> 键(在文本字段上写入 Generate toString)

Be clear when adding toString() as to the audience of the generated text.添加 toString() 时要明确生成文本的受众。 Some frameworks use the toString() method to generate end user visible text (eg certain web frameworks), whereas many people use toString() methods to generate debugging / developer information.一些框架使用 toString() 方法生成最终用户可见的文本(例如某些 Web 框架),而许多人使用 toString() 方法生成调试/开发人员信息。 Either way, make sure that you have enough uniqueness in the toString implementation to satisfy your requirements.无论哪种方式,请确保您在 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 实现会生成开发人员信息,因此如果可能的话,这通常是我推荐的模式,但是如果您正在从事具有不同想法/期望的项目,您可能会感到困惑......

Just noticed - In NetBeans IDE you 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 中,您可以通过选择要生成的字段来生成 toString() 方法以进行right click->insert code或使用快捷方式ALT+INSERT然后选择 toString()。

Way it looks is :它的样子是:

@Override
public String toString() {
    return "ClassName{"+"fieldName="+fieldName+'}';
}

Its great way to debug and no need for additional libs.这是调试的好方法,不需要额外的库。

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 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM