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.
This allows you to hint Alt+Enter on a static method and gives the source hint "Add static import for ...."
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
I created a template with the following for
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:
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.
You might also enjoy reading -
- Netbeans code template for SLF4J logging
- 5 Reasons Why NetBeans Rocks
- Getting nice font rendering in Netbeans 7 on Ubuntu 12.04
- NetBeans 6.7 Broke My Parameterized Tests