14.1 The GrailsCompileStatic Annotation

GrailsCompileStatic

The GrailsCompileStatic annotation may be applied to a class or methods within a class.

  1. import grails.compiler.GrailsCompileStatic
  2. @GrailsCompileStatic
  3. class SomeClass {
  4. // all of the code in this class will be statically compiled
  5. def methodOne() {
  6. // ...
  7. }
  8. def methodTwo() {
  9. // ...
  10. }
  11. def methodThree() {
  12. // ...
  13. }
  14. }
  1. import grails.compiler.GrailsCompileStatic
  2. class SomeClass {
  3. // methodOne and methodThree will be statically compiled
  4. // methodTwo will be dynamically compiled
  5. @GrailsCompileStatic
  6. def methodOne() {
  7. // ...
  8. }
  9. def methodTwo() {
  10. // ...
  11. }
  12. @GrailsCompileStatic
  13. def methodThree() {
  14. // ...
  15. }
  16. }

It is possible to mark a class with GrailsCompileStatic and exclude specific methods by marking them with GrailsCompileStatic and specifying that the type checking should be skipped for that particular method as shown below.

  1. import grails.compiler.GrailsCompileStatic
  2. import groovy.transform.TypeCheckingMode
  3. @GrailsCompileStatic
  4. class SomeClass {
  5. // methodOne and methodThree will be statically compiled
  6. // methodTwo will be dynamically compiled
  7. def methodOne() {
  8. // ...
  9. }
  10. @GrailsCompileStatic(TypeCheckingMode.SKIP)
  11. def methodTwo() {
  12. // ...
  13. }
  14. def methodThree() {
  15. // ...
  16. }
  17. }

Code that is marked with GrailsCompileStatic will all be statically compiled except for Grails specific interactions that cannot be statically compiled but that GrailsCompileStatic can identify as permissible for dynamic dispatch. These include things like invoking dynamic finders and DSL code in configuration blocks like constraints and mapping closures in domain classes.

Care must be taken when deciding to statically compile code. There are benefits associated with static compilation but in order to take advantage of those benefits you are giving up the power and flexibility of dynamic dispatch. For example if code is statically compiled it cannot take advantage of runtime metaprogramming enhancements which may be provided by plugins.