Inserting Guava Preconditions in Eclipse

Eclipse has the well-known surround-with feature (keyboard shortcut ctrl-alt-Z.) Something I’ve always wanted was to find an easy way to surround expressions with Preconditions. For example, select the right hand side of

this.firstName = firstName;

to make

this.firstName = Preconditions.checkNotNull(firstName);

Unfortunately, Surround With only works with full line selections, which means you can’t select the right hand side of the statement; you can only select the full line. There is, however, another work around, which I will enumerate here: Preferences > Java > Editor > Templates > New… Enter the following values: Name: checkNotNull Context: Java Description: Add Guava Precondition Pattern: ${:import(}Preconditions.checkNotNull(${word_selection}) Repeat this twice more for checkArgument and checkState, and repeat each of those for its static import version. I have supplied a Workspace Mechanic-compatible .epf [gist] that sets all six of these, but use it carefully: the preference would override all other customized templates.

Now let’s quickly describe how to import and use these.

If you use the Workspace Mechanic, store the file in an appropriate place (by cloning the git repository.) Otherwise you can import the file using File > Import > General > Preferences.

Once the preferences are imported, you can use the completion proposal keyboard shortcut (ctrl-space on most platforms,  cmd-space on OSX) it brings up the content assistant. Look in the lower-right corner. It tells you to press that combination again to get another set of completion proposals; in this case it’s Template Proposals.

The template proposals are are there!

Of course, checkArgument and checkState accept boolean arguments, so you might not find them quite as useful, or perhaps useful in a different context.

If you’re having trouble, or you want to configure how the content assistant selects proposal types, navigating to Preferences > Java > Editor > Content Assist > Advanced.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s