Code generation and formatting with Eclipse IDE
Introduction
In this post, we will look at some of the programming tips with Eclipse IDE like automatic code generation and code formatting. Code formatting allows us to indent the code for better readability of the code. To format the code, select Right-click -> Source -> Format. This option would automatically indent the code.
Code Indentation
Let’s unindent the code, as shown in the below picture:
Now, you can format the indentation using the option.
Using this option, Eclipse removes unwanted spaces and tab space in the code and indents your code. Properly indented code increases the readability of the code.
The keyboard shortcut for the same is Ctrl + Shift + F . This shortcut helps you to save time if your are formatting code for several classes at a time.
Code generation
Using Eclipse IDE, you can generate code automatically for some methods in a Java class. You can generate code for setter/getter methods, constructors, hashcode(), equals() and toString() methods.
Getter/Setter
To generate getter and setter methods, select the instance variables in the class and right-click -> Source -> Generate Setters and Getters… option. choose the variables and click on Generate button.
Variables selection:
toString()
toString() method generation:
Code Listing
The auto-generated code for Book class is shown below. Most of the code in the class is generated by Eclipse IDE. These options reduce the time taken to code in Eclipse.
package com.testingdocs; public class Book { private String author; private double price; private String title; public Book(String author, double price, String title) { super(); this.author = author; this.price = price; this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public static void main(String[] args) { // TODO Auto-generated method stub Book bookObject = new Book("Sears and Zemansky", 99.99, "University Physics"); System.out.println(bookObject.toString()); } @Override public String toString() { return "Book [author=" + author + ", price=" + price + ", title=" + title + "]"; } }
Eclipse Tutorials on this website can be found at:
https://www.testingdocs.com/eclipse-tutorials
For more details on the Eclipse IDE, visit the official website at:
https://www.eclipse.org