Skip to content

Instantly share code, notes, and snippets.

@glaforge
Last active August 10, 2016 20:17
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save glaforge/4563430 to your computer and use it in GitHub Desktop.
@interface Min {
int value() default 0
}
@interface Max {
int value() default 100
}
import org.codehaus.groovy.transform.AnnotationCollectorTransform
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
class RangeAnnotationProcessor extends AnnotationCollectorTransform {
List<AnnotationNode> visit(AnnotationNode collector, AnnotationNode usage, AnnotatedNode annotated, SourceUnit src) {
def minExpr = usage.getMember('from')
def maxExpr = usage.getMember('to')
def (minAnno, maxAnno) = getTargetAnnotationList(collector, usage, src)
minAnno.addMember('value', minExpr)
maxAnno.addMember('value', maxExpr)
usage.members.remove('from')
usage.members.remove('to')
return [minAnno, maxAnno]
}
}
new GroovyShell(this.class.classLoader).evaluate '''
import groovy.transform.AnnotationCollector
@Min @Max
@AnnotationCollector(processor = 'RangeAnnotationProcessor')
@interface Range {}
class Room {
@Range(from = 1, to = 4)
int numberOfPersons
}
println new Room()
'''
@Wadeck
Copy link

Wadeck commented Jun 24, 2015

How do you manage the case of a processor that have a package ?

In my case, I have a "standard" structure of package, but I can't link the processor to the annotation. I tried the class full name (with package) and simple name (like your example).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment