How to use ‘static import’ in Java

[toc]

I was just reminding myself how to write a generics class in Java, and for some reason while I was doing that I wanted to use the Java ‘import static’ capability so instead of typing this:

System.out.println("foo");

I could just use this:

out.println("foo");

The only thing you have to do to make this happen is to use this import static statement at the top of your class:

import static java.lang.System.out;

To take this a step further, you can import both System.out and System.err like this:

import static java.lang.System.out;
import static java.lang.System.err;

A complete example

To show a full example of how this works, here's a small but relatively complete Java class that puts this all together:

import static java.lang.System.out;
import static java.lang.System.err;

class Foo {

  public static void main(String[] args) {
    out.println("foo");
    err.println("bar");
  }

}

This approach doesn't make much sense in a small application, but if you get tired of constantly typing "System.out.println" in a large application, it can save you some typing, and make your code less verbose.

A more common example

I just used this again today to import a list of static constants for a Java football game I’m writing. The static import statement at the top of my class looks like this:

import static com.valleyprogramming.playcaller.Constants.*;

This lets me refer to positions like this:

if (position == QB) ...

rather than having to type this:

if (position == Constants.QB) ...

where QB is a field in the Constants class.