编写一个groovy方法以使用带注释的字段提取所有嵌套类

时间:2016-01-12 05:21:15

标签: groovy annotations

我创建了对象,然后尝试将它们添加到列表中。它能够构建地图,但问题是对象图很复杂而且解决方案不是可维护的

Person person=new Person(name:"Dennis Carter",department:"Engineering",manager..)

Retail retail=Retail(field :"Fixed Price", p:person)
list l=[]

//manually add to list

l<<person.manager
l<<manager.department
l<< manager.address
//etc

//...
Finder f=new Finder(l)
println "Manp is ${f.myMap"

class Finder {
    Finder(def obj){
        for(element in obj )
            addToMap(element)
    }

    def myMap=[:]

    def addToMap( obj) {
        def ops=[]
        def fans=[]
        if(obj){
            ops= obj.class.declaredFields
            for(Field f : ops ){
                fans=   f.annotations
                for(Annotation an : fans){
                    if(an.annotationType()==myAnnot) {
                        MyAnnot well=(MyAnnot)an
                        myMap[well.used()]=well.type()
                    }
                }
            }
        }
        println "Your map is finally ${myMap}"
    }
}

class Retail {
    @MyAnnot
    String field
    Person p
}

class Person{
    @MyAnnot
    String name

    @MyAnnot
    Manager currentManager

    //...
}

class Manager{
    @MyAnnot
    String name
}

我希望能够访问对象图并找到带注释@MyAnnot的所有嵌套类。例如,Person类没有注释,但其嵌套字段具有MyAnnot注释,依此类推

0 个答案:

没有答案