2011-06-17 69 views
3

是否有一種方便的方式來迭代Object的屬性並檢查每個對象的註釋?在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,這似乎是做到這一點的方式: ' 高清findAllPropertiesForClassWithAnotation(OBJ,annotClass){ obj.properties.findAll {道具 - > obj.class.declaredFields.find {場 - > field.name == prop.key && field.declaredAnnotations * .annotationType()。含有(annotClass) }} } ' 如何 –