Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.format("Name: %s Age: %d Height %f", name, age, height); } 
like image 893
Gordon Avatar asked Apr 16 '10 13:04

Gordon


People also ask

Is the toString method automatically called?

Automatic Call of toString() When a parameter should be a String reference, but is a reference to another type of object, Java calls the object's toString() method to create a String and then uses the resulting String reference.

How do we call toString () method?

Your toString() method is actually being called by the println method.


1 Answers

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?

like image 112
Dónal Avatar answered Sep 20 '22 03:09

Dónal