开发者

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?

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.f开发者_如何学Pythonormat("Name: %s Age: %d Height %f", name, age, height);
}


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?


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.


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.


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

       }

}


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.

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

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

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

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



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)


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


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.


Considering some old answers including @Steve's, I'd like to add answer as per latest library.

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 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜