Java – static import

static import is an interesting feature absent in C#. The Java pages warns to not abuse it. http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

It allows you to reference static methods within a class as if they belonged to the current class.

Before Static Import:

import org.junit.*;
…
Assert.fail("Not yet implemented");

After Static Import:

import static org.junit.Assert.*;
…
fail("Not yet implemented");

Thoughts:

I think it’s one of those features that you can live without, but it is neat. In cases where you’re referencing a class with a large number of static methods it removes the need to wrap every method in a helper method to save the small bit of typing involved in referencing the external class. I could see it also aiding in refactoring – with static import, your code can directly reference an external static method and if you later choose to use local methods instead, you need only remove the static import and add the local method. Without the static import you would need to update every place in code that used the static method.

Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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