Blog About Contact

Dealing With Static Imports in Netbeans IDE

Published Tue, 29 Jan 2013 • 1 comments

Static imports can be quite a nice feature of the Java language for improving code readability and clarity, however they can be a bit of a pain to setup for use easily from within your IDE.

In Netbeans there's a couple of features / techniques that I use to make using static imports easier.

The first and most important is to enable the "JDK 1.5 and later > Static Imports" source hint.

Options panel of Netbeans showing source hint

This allows you to hint Alt+Enter on a static method and gives the source hint "Add static import for ...."

Example use of static import source hint

This allows you to add imports much more easily, but I find there are sets of classes that I'm always wanting to static import from, particular when writing unit tests, I want to import from the JUnit Asserts and Mockito's matchers and core library.

To go through these one by one and keep adding them gets pretty tedious, so a workaround I've come up with is to create a source template which has the common imports included.

A code template is an abbreviated form which you type and hit Tab to expand it. For example sout+Tab expands to System.out.println("")

I created a template with the following for sti+Tab :

import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Mockito.*;

Here's where in the Netbeans options it lives:

Code template options in Netbeans

This means you can type sti+Tab when at the top of a class and get these static imports very quickly. I use this in combination with the "Fix Imports -> Remove Unused Imports" and "Organise Imports" features after I'm done writing the test code to remove unused imports and expand the wildcards into fully qualified imports.

About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -

Discuss / Comment

There are 1 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Valid email address required.
Posting message, please wait...