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

蓝咒 提交于 2019-11-26 18:25:27

问题


Is it good or bad practice auto-generating toString methods for some simple classes?

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.

private String name;
private int age;
private double height;

public String toString(){
   return String.format("Name: %s Age: %d Height %f", name, age, height);
}

回答1:


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()...

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?




回答2:


I personally like to implement a toString method for all objects, as it helps in debugging.

I would look into using the Apache Commons ToStringBuilder.

You can implement a simple toString method using reflection as follows:

public String toString() {
   return ToStringBuilder.reflectionToString(this);
}

Using this method, you will not have to update your toString method if/when fields are added.




回答3:


If you use lombok they have a @ToString annotation which will generate the toString for you.

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 lombok you don't have to do that.




回答4:


To add to Steve's and Don's answers (+1 for them) :

Make your toString() method simple, make sure it nevers triggers expections (especially be aware of fields that could be null).

If possible, don't call other methods of your class. At least, be sure that your toString() method doesn't modify your object.

And be aware of silly exception-toString loops:

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

       }

}



回答5:


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.

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 :)




回答6:



Shortcut to generate toString() method


  1. Press Alt + Shift + S + S (double)
  2. Right click -> Source -> Generate toString() ...
  3. Go to Source menu -> Generate toString() ...
  4. Go to Windows menu -> Preferences -> General -> Keys (Write Generate toString on text field)



回答7:


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.

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...




回答8:


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().

Way it looks is :

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

Its great way to debug and no need for additional libs.



来源:https://stackoverflow.com/questions/2653268/what-are-the-shortcut-to-auto-generating-tostring-method-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!