Reading — step 1 of 5
Learn
Groovy has compile-time annotations called AST transformations that rewrite your code before compilation. The standard library ships dozens.
Built-in @CompileStatic — turn off Groovy's dynamic dispatch, get Java-level performance + type checking:
import groovy.transform.CompileStatic
@CompileStatic
class Calculator {
int add(int a, int b) {
return a + b
}
}
With @CompileStatic, the compiler:
- Resolves all method calls statically
- Checks types at compile time
- Disables
metaClassmodifications (calls go direct) - Performance approaches Java
@TypeChecked — type checking only, dynamic dispatch preserved:
@TypeChecked
def greet(String name) { ... } // type errors caught
@Memoized — caches function results:
class Service {
@Memoized
String expensiveOp(String key) {
// computed once per key
Thread.sleep(1000)
return "result-${key}"
}
}
@Builder — generates a fluent builder:
import groovy.transform.builder.Builder
@Builder
class Person {
String name
int age
}
def p = Person.builder().name("Ada").age(36).build()
@Singleton — auto-implements singleton pattern:
@Singleton
class Config {
String env = "prod"
}
Config.instance.env
@Immutable — makes the class immutable, generates equals/hashCode/toString:
@Immutable
class Point {
int x
int y
}
def p = new Point(3, 4)
p.x = 10 // ReadOnlyPropertyException
@Sortable — generates Comparable based on declared field order:
@Sortable
class User {
String name
int age
}
Custom AST transformations are possible (define @interface + ASTTransformation class) but rarely needed — the built-in set covers most use cases.
Major frameworks built on AST transformations:
- Spock —
@Specificationrewrites your test code - Grails / Micronaut — controller/route annotations
- Geb — page-object DSL
These transformations save HUGE amounts of boilerplate compared to plain Java.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…