Question
I created a java interface for my annotation. I am now writing a class and I would like to print the annotation values so it shows in the log message. Is this possible? Here is my test case and let me know if I am doing this wrong:
- @Retention(RetentionPolicy.RUNTIME)
- public @interface TestCase {
- String someID()
- }
- class Checkout{
- @TestCase(someID="12345")
- def "a dynamic method name"() {
- // My test steps.....
- }
- }
Use StackTraceUtils.sanitize to get the current method and use reflection to iterate through the annotations:
- import java.lang.annotation.Annotation
- import java.lang.annotation.Retention
- import java.lang.annotation.RetentionPolicy
- import java.lang.reflect.Method
- import org.codehaus.groovy.runtime.StackTraceUtils
- @Retention(RetentionPolicy.RUNTIME)
- public @interface TestCase {
- String someID()
- }
- class Checkout{
- @TestCase(someID="12345")
- def "a dynamic method name"() {
- printTestCaseId()
- // My test steps.....
- }
- def printTestCaseId() {
- def stack = StackTraceUtils.sanitize(new Throwable()).stackTrace[1]
- def method = getClass().declaredMethods.find { it.name == stack.methodName }
- printf("method=${method}\n")
- def someID = method.annotations[0].someID()
- printf("someID=${someID}\n")
- assert someID == "12345"
- }
- }
- def co = new Checkout()
- co."${'a dynamic method name'}"()
If you want to iterate all methods and corresponding annotations from a class, you can try below sample code:
- import java.lang.annotation.Annotation
- import java.lang.annotation.Retention
- import java.lang.annotation.RetentionPolicy
- import java.lang.reflect.Method
- @Foo('class')
- class A{
- def name = "A"
- @Foo('method')
- def test()
- {
- printf("testing")
- }
- }
- A a = new A()
- printf("%s\nClass %s\n", a.class.annotations[0], a.class.name)
- a.class.declaredMethods.each{ m->
- printf("\tMethod:%s (%d)\n", m.name, m.annotations.size())
- m.getDeclaredAnnotations().each{ an->
- printf("\t\tAnnotation->%s\n", an)
- }
- if(m.isAnnotationPresent(NO.class)) {
- printf("\t\t%s\n", m.getAnnotation(NO.class))
- }
- }
Supplement
* Documentation - User Guide - Annotations with Groovy
* Java SE 6 技術手冊 - 第 17 章 Annotation
沒有留言:
張貼留言