Static Import Usage Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Groovy's static import capability allows you to reference imported classes as if they were static methods in your own class. This is similar to Java's static import capability but works with Java 1.4 and above and is a little more dynamic than Java in that it allows you to define methods with the same name as an imported method as long as you have different types. If you have the same types, the imported class takes precedence. Here is a sample of its usage:

The first static import illustrates defining LIGHT_GRAY as if it was defined locally as a static field.

The next two examples show renaming (called aliasing) of a field and a method respectively.

The final example illustrates wild-carding for fields and methods and also selecting between the locally defined toHexString and imported toHexString based on parameter matching.

As another example, here is how to statically import some of the Math functions:

Note: Groovy does not check beyond your import class if what you statically import exists. If you import a nonexisting method, field or property Groovy will not fail at compile time, but later when executing the compiled code.

Java language guide recommends to use static imports very sparingly because they can harm readability when overused.

 

Search

Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified