你如何阅读groovy中的现有方法@annotations?

时间:2017-10-31 13:00:58

标签: groovy

我试图在@XmlElement中使用Top myxml注释方法,但它是`myxml.methods [1]

import javax.xml.bind.annotation.*
import groovy.transform.*
import javax.xml.bind.*

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@TupleConstructor
class Top {
    String myBackingField

    @XmlElement
    public String getChildElement() {
        return myBackingField
    }

}
def myxml = new Top("child_one")

到目前为止,我得到了:

def mymethod = parsed.metaClass.methods.find { it.name == 'getChildElement' }

CachedMethod API无法访问注释。

1 个答案:

答案 0 :(得分:0)

CachedMethod开始,您可以使用CachedMethod.getCachedMethod()转到java.lang.reflect.Method,然后您可以使用Method.getAnnotations()Method.isAnnotationPresent()

def mymethod = myxml.metaClass.methods.find { it.name == 'getChildElement' }
// mymethod.class is org.codehaus.groovy.reflection.CachedMethod
mymethod.cachedMethod.annotations // [@XmlElement(name=##default, namespace=##default, 
                                  // type=class XmlElement$DEFAULT, defaultValue=, 
                                  // required=false, nillable=false)]

要获得具有该注释的方法,您可以

def mymethods = myxml.metaClass.methods.findAll {
  it.cachedMethod.isAnnotationPresent(XmlElement)
}
mymethods[0].class // CachedMethod backed by Method with XmlElement annotation