Disable Eclipse formatting for certain sections of code only

In a previous tip, I showed how to automatically format code every time you save in Eclipse or how to manually format by pressing Ctrl+Shift+F. These work great most of the times but sometimes you want to exclude a certain block of code from formatting, often because the formatting turns out unreadable (ie. ugly) for that particular piece of code.

Eclipse allows you to disable formatting for a certain block or section of code by surrounding that code with formatter comments, known as Off/On tags. And you can also make generating those comments around a block of code extremely simple by creating a simple template.

Continue reading

Compare two workspace or external files in Eclipse

We all have our favourite diff tools for comparing files and it’s probably not Eclipse itself, unless you’re comparing version controlled files.

But sometimes you’ll want to compare two files from within Eclipse (whether they are in your workspace or external files) either because it’s quicker or you don’t have your own diff tool to hand.

Eclipse offers two ways of comparing files with each other. One of them is appropriately called Compare with Each Other. Although this is often the suggested way to compare files, it’s not easy to use and doesn’t work with external files. This post will focus on another Eclipse feature called Compare with Other Resource that makes things go a bit smoother and handles external files but it will also cover using Compare with Each Other.

Continue reading

Generate, rename and delete getters/setters instantly in Eclipse

Despite the arguments and debates about getters and setters in Java, the fact is that they’re a reality and you have to work with them.

But managing getters and setters is a time-consuming effort. Creating a getter/setter for 5 fields in a class can take minutes, renaming one is error-prone and deleting one is just plain inconvenient.

There are options like Project Lombok (that implicitly creates getters/setters without the need to code them) and you could avoid getters/setters altogether by redesigning your classes.

But these options aren’t always available, so it’s a good thing Eclipse has some handy features for managing getters and setters. Combined with the ability to generate constructors based on fields, you can get the boilerplate code out of the way in seconds and get on with the real coding.

Continue reading

Convert nested/anonymous classes into top level classes using Eclipse refactoring

Nested classes, eg. anonymous classes, are often more convenient than creating separate classes, especially when working with something like the Command pattern or event listeners. For example:

JButton button = new JButton();
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // ... Do something useful
    }
});

But there comes a point when the nested class becomes so bulky that code becomes unreadable. And sometimes you want to reuse the same class in another place – something that’s difficult with anonymous inner classes.

The answer would be to change the nested class into a top level public class (or a first-class citizen, if you like) that exists in its own file (eg. SomethingUsefulActionListener.java). But doing this manually can take a lot of time and is error-prone.

Eclipse has a couple of refactorings and quick fixes that help to make the job a lot easier. Converting an anonymous inner class to a top level class requires two refactorings only and will take you a couple of seconds instead of minutes. A (named) inner class takes only one refactoring. And passing arguments to the new class is also easy if you use some of Eclipse’s Quick Fixes.

Continue reading

Add comments and Javadocs in Eclipse with a single keystroke

When you want to work with comments in Eclipse, you could use the slow way of moving to the start of the line, pressing // and then repeating this for all the lines you have.

Or you could use the quick way of adding a comment with a single keystroke no matter where the cursor’s positioned in the statement.

The same goes for Javadocs – there are just too many things to type before you can start commenting the good stuff. That’s why Eclipse also has a shortcut that let’s you add Javadoc to a field, method or class.

Continue reading

Extract constants from strings and numbers with Eclipse refactorings

For readability’s sake, it’s almost always a good idea to replace magic numbers and string literals with constants. That’s all good, but it can take a bit of time to refactor these to constants, especially strings or parts of strings.

For example, in the code below we want to refactor “shovel and spade” to a private static final String called TOOLS. To do that manually would take some time. It goes even slower if we only want to extract “spade” to a constant because we first have to convert the string to a concatenation.

String tools = "shovel and spade";
...
String otherTools = "shovel and spade";

Luckily, Eclipse has a couple of ways to instantly convert literals to constants. Coupled with tools to speed up string selection and to pick out part of a string, you have the ability to create a constant in about 2 seconds flat. I’ll discuss all these features below.

Continue reading

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

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

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

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