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

后端 未结 9 1290
遥遥无期
遥遥无期 2020-12-03 13:17

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 th

相关标签:
9条回答
  • 2020-12-03 14:10

    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);
               }
    
           }
    
    }
    
    0 讨论(0)
  • 2020-12-03 14:14

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

    0 讨论(0)
  • 2020-12-03 14:14

    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 讨论(0)
提交回复
热议问题