2016-03-31 5 views
0

注釈を介してディスパッチメソッドを作成することは可能ですか?私は、次のシナリオを作成しようとしています:AnnotationReferenceから注釈を取得し、ディスパッチメソッドを作成

def generateField(FieldDeclaration field, ClassDeclaration clazz) { 
    ''' 
     «field.annotations.map[it.generateAnnotation(field)].join» 
     ''' 
} 

def dispatch generateAnnotation(Password annotation, FieldDeclaration field){ 
    '''//Password field''' 
} 

def dispatch generateAnnotation(Boolean annotation, FieldDeclaration field){ 
    '''//Boolean field''' 
} 

定義された注釈を:

annotation Boolean { 

} 

annotation Password { 

} 

私はAnnotationDeclarationクラス上の注釈にアクセスするにはどうすればよいですか?

答えて

1

AnnotationReferenceは、注釈のインスタンスを表します。インスタンスの値と型にアクセスするためのAPIを提供します。

val passwordAnnotation = Password.findTypeGlobally 
val booleanAnnotation = Boolean.findTypeGlobally 

val AnnotationReference annotation = field.annotations.head 
// get a type 
val annotationType = annotation.annotationTypeDeclaration 
// check whether the type is Password 
if (passwordAnnotation.isAssignableFrom(annotationType)) { 
    // get a value of 'myValue' field as integer 
    val int value = annotation.getIntValue('myValue') 
    … 
} else if (booleanAnnotation.isAssignableFrom(annotationType)) { 
    … 
} else if (…) { 
    … 
} 
+0

ありがとうございます。私はif/elseとdispatchメソッドを避けたいと思っていました。私はすでにそれと同様の方法を見つけました。 – aphex

関連する問題