2011-06-17 1 views
3

オブジェクトのプロパティを繰り返し処理し、それぞれの注釈をチェックする便利な方法はありますか?Groovyのプロパティ注釈イントロスペクション

+0

あるとは思いません。たぶん、あなたが達成しようとしていることについて、より多くの情報を提供することができます。 –

答えて

8

あなたは、このようにそれを行うことができます。この場合

// First, declare your annotation 
import java.lang.annotation.* 

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.FIELD) 
public @interface MyAnnot { 
} 

// Then, define your class with it's annotated Fields 
class MyClass { 
    @MyAnnot String fielda 
    String fieldb 
    @MyAnnot String fieldc 
} 

// Then, we will write a method to take an object and an annotation class 
// And we will return all properties of the object that define that annotation 
def findAllPropertiesForClassWithAnotation(obj, annotClass) { 
    obj.properties.findAll { prop -> 
    obj.getClass().declaredFields.find { 
     it.name == prop.key && annotClass in it.declaredAnnotations*.annotationType() 
    } 
    } 
} 

// Then, define an instance of our class 
MyClass a = new MyClass(fielda:'tim', fieldb:'yates', fieldc:'stackoverflow') 

// And print the results of calling our method 
println findAllPropertiesForClassWithAnotation(a, MyAnnot) 

が、これはプリントアウト:

[fielda:tim, fieldc:stackoverflow] 

はそれが役に立てば幸い!

+0

ありがとう、これは便利でした!私はGroovyから期待できる超エレガントではありませんが、それは動作します:) – Pavlo

+0

@ pavlo同じもののjavaバージョンに比べて優雅? –

+0

は使用Groovyの2.4.5は、これはそれを行うための方法のようです: - > obj.class.declaredFields.find {フィールド ' デフfindAllPropertiesForClassWithAnotation(OBJ、annotClass){ obj.properties.findAll {小道具 - > field.name == prop.key && field.declaredAnnotations * .annotationType()。(annotClass)が含まれてい }} } ' –