Java already has static imports, but Groovy takes it to the next level. In a previous post we learned how we use the
as keyword to assign a class we import to a variable in the
import statement. But with static imports we can do this even for static methods and properties. This makes for code which may confuse us, but if we look at the import section all will be revealed.
import static HttpURLConnection.HTTP_OK // Normal Java static import. import static HttpURLConnection.HTTP_OK as okay import static HttpURLConnection.setFollowRedirects as redirect import java.net.HttpURLConnection as http // Non static import. redirect false // HttpURLConnection.setFollowRedirects(false) assert false == HttpURLConnection.followRedirects def c = (http) 'http://mrhaki.blogspot.com'.toURL().openConnection() assert c instanceof HttpURLConnection assert okay == c.responseCode assert HTTP_OK == c.responseCode