Generate class constructors in Eclipse based on fields or superclass constructors

You’ll often need to add a constructor to a class based on some/all of its fields or even based on constructors of its superclass. Take the following code:

public class Contact {
    private String name, surname;
    private int age;

    public Contact(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

That’s 5 lines of code (lines 5-9) just to have a constructor. You could write them all by hand, but writing a constructor that accepts and initialises each field takes a lot of time and becomes irritating after a while. And creating constructors from a superclass can take even longer because the superclass can define multiple constructors that you need to reimplement.

That is why Eclipse has two features to help you generate these constructor instantly: Generate Constructor using Field and Generate Constructor from Superclass. Both features will generate a constructor in seconds, freeing you up to get to the exciting code. You’ll also see how to add/remove/reorder arguments of an existing constructor based on fields defined in the class.

Continue reading

JUnit testing made easier with Eclipse templates

When you’re writing JUnit tests, you’ll often find yourself repeating the same boilerplate code. Take the following code:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class EngineTest {
    @Before
    public void setup() {
        ...
    }

    @Test
    public void test() throws Exception {
        ...
    }

    @After
    public void tearDown() {
        ...
    }
}

If you want to add a test, you have to somehow add lines 3, 11, 12 and 14 before you even get to the actual test. The same holds for setup and teardown code. We know that Eclipse can help with adding imports automatically when you save or autocomplete, but it still takes time to get everything in place.

Eclipse templates can help take away the drudgery by adding all this boilerplate code automatically. It can automatically add a test, setup and teardown methods together with calls to assertEquals, assertTrue and others. I’m assuming JUnit 4 in all the templates. If you’re new to templates, then see this tip to get an overview.

Continue reading

Automatically place a semicolon at the end of Java statements in Eclipse

We all know that Java statements are terminated by a semicolon (;), but they’re a bit of a pain to add to the end of a line. One way would be to press End (to move to the end of the line) then press semicolon, but this is tedious. Because this is something that you do often it’s worth learning how to do this faster.

It’s a good thing Eclipse can automatically put the semicolon at the end of the line, no matter where you are in the statement. It’s as easy as setting one preference and there’s a bonus preference for adding braces to the correct position as well. For something so small, it saves a lot of time.

So in the example below, if you imagine that your cursor is placed after the word blue since you were editing the string. Pressing semicolon will cause Eclipse to place the semicolon after the closing bracket at the end. Nice.

System.out.println("The house is blue")

Continue reading

The fastest ways to navigate views in Eclipse using the keyboard

With so many views in Eclipse (around 50 for a default install), it can become difficult to navigate them all, especially when you don’t want to reach for the mouse all the time. As I’ve mentioned in a previous post on how to manage keyboard shortcuts, learning how to use the keyboard efficiently can save you oodles of time later on.

Fortunately, Eclipse has a number of ways to navigate between views using only the keyboard. I’ll discuss the Show View shortcuts, the Show Views dialog, Quick Access and then view cycling, with some advice on when to use which one. There’s also a bonus tip on how to activate the editor with the keyboard once you’re done with a view.

Continue reading

Add, remove and reorder a method’s arguments instantly across multiple classes in Eclipse

When refactoring, one thing that sometimes changes is a method’s signature (ie. its return type, number of arguments, argument types and order).

For some it may not happen that often, but the job becomes difficult when you have a dozen or more classes that call that method. All of them need to be changed to match the new signature and this can take a long time to change.

Fortunately, Eclipse has a refactoring called Change Method Signature that makes this easy, allowing a signature change in almost no time across any number of classes. This can be a huge timesaver when you need it and save you hours of frustration trying to fix red crosses in Eclipse.

Continue reading

How to manage keyboard shortcuts in Eclipse and why you should

When I use Eclipse I try and use shortcuts all the time. They really make me work faster and give me time to focus on getting the code out rather than slowing down to invoke IDE commands with the mouse.

Because people work differently and on different things, it’s important to manage keyboard shortcuts to suit the way you work. So it’s good that Eclipse makes it really easy to change shortcuts and also to view shortcuts for the commands you use a lot.

I’ll discuss how to change keyboard shortcuts, how to avoid conflicts with existing ones, why it’s a good thing to manage shortcuts and then end off with some examples of common shortcuts that you should add to you arsenal. Continue reading

Generate static imports in Eclipse on autocomplete for JUnit Assert, StringUtils and others

Eclipse normally adds import statements for you when you autocomplete a type, press Ctrl+Shift+O or organise imports when you save. However, by default it doesn’t do the same for static imports, something you’ll miss when using classes like JUnit’s Assert and Apache Commons’ StringUtils. This means having to add import statements manually, which takes unnecessary time.

So, in the code below, I want to be able to autocomplete assertEquals (line 7) and have Eclipse add a static import for org.junit.Assert.assertEquals (line 1).

import static org.junit.Assert.assertEquals;
...
public class MyTest {
   @Test
   public void testSomething() throws Exception {
      assertEquals(1, 1);
   }

Now, the good news is that there is a way to automatically add static imports when you use autocomplete. It’s done via a preference that tells Eclipse which static classes you want to include for Content Assist (autocomplete). I show you how to do this below.

The bad news is that there doesn’t seem to be a way to tell the Organise Imports command to add static imports. However, a working autocomplete should already cater for 90% of your coding needs, so the bad news isn’t that bad.

Continue reading

Convert string concatenations into StringBuilder or MessageFormat calls with Eclipse’s Quick Fix

Eclipse sports a really nice Quick Fix that turns string concatenations into the recommended calls to StringBuilder. It saves you the time of creating a variable, having to pull out each of the string parts into a call to StringBuilder’s append and then using the string with toString().

So with one key, it will turn code like this:

System.out.println("The year " + year + " is a leap year.");

Into this:

StringBuilder message = new StringBuilder();
message.append("The year ");
message.append(year);
message.append(" is a leap year.");
System.out.println(message.toString());

Continue reading

Checkout multiple projects automatically into your Eclipse workspace with Team Project Sets

When working in Eclipse, you’ll often end up with a number of projects in your workspace that constitute an application. You could have a multi-tiered system with a web, server and database project and other miscellaneous ones. Or if you’re an Eclipse RCP developer, you could end up with dozens of plugins each represented by a project.

Although multiple projects give you modularity (which is good), they can make it difficult to manage the workspace (which is bad). Developers have to check out each project individually from different locations in the repository. Sometimes they even have to get projects from multiple repositories. This is a painstakingly long and error-prone task.

But an easier way to manage multiple projects is with Eclipse’s Team Project Sets (TPS). Creating a workspace becomes as easy as importing an XML file and waiting for Eclipse to do its job. Yes, there are other more sophisticated tools out there that do this and more (eg. Maven and Buckminster) but team project sets are a good enough start if you haven’t got anything set up and may be good enough for the longer term as well, depending on how your team works.

Continue reading

Join/split if statements and rearrange expressions using Eclipse Quick Fix

A common cause of bad readability is nested if statements, especially when they could be combined into one if with an AND (&&). This also opens the opportunity to extract private methods to make the if more readable. While you’re at it, you might also want to rearrange the expressions so they make more logical sense.

But making these changes can be tedious and time consuming and often error-prone. It may not happen that frequently, but when it does you want it to go as fast as possible.

Eclipse comes to the rescue with a quick fix that allows you to join or split the statements in one keystroke. And the quick fix allows you to rearrange expressions on the if statement as well.

Continue reading