使用反射调用java/groovy对象的静态方法

est*_*ord 2 java reflection groovy

我正在研究一个groovy单元测试类,它包含一组规则,用于判断文件内容是否格式正确.(没有使用适当的规则引擎,它只是利用Groovy的断言功能以一种模糊地类似于规则引擎的方式进行验证.)我在想我可以创建一个名为FireAllRules的方法,如下所示:

public static void FireAllRules(File file)
{
    for(def method in Class.getMethods)
    {
        if(method.name.indexOf("rule" == 0) method.invoke(file);
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望循环接收的所有方法都是静态的,我注意到在调试过程中,我的规则方法都没有包含在Class.getMethods()枚举中.理想情况下,我只想循环遍历我个人写入类的方法,而不是通过几十种与java.Object一起出现的无趣的方法进行排序.有没有办法在运行时使用反射迭代这些静态方法?

tim*_*tes 5

鉴于:

class Test {
  public static testThis() {
    println "Called testThis"
  }

  public static woo() {
    println "Called woo"
  }

  public static testOther() {
    println "Called testOther"
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以做:

Test.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
  it.invoke( Test )
}
Run Code Online (Sandbox Code Playgroud)

打印:

Called testOther
Called testThis
Run Code Online (Sandbox Code Playgroud)

执行类的静态测试方法的更通用的方法是:

def invokeClass( clazz ) {
  clazz.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
    it.invoke( clazz )
  }
}

invokeClass( Test )
Run Code Online (Sandbox Code Playgroud)

  • @estanford您可以尝试`it.invoke(clazz,null)`奇怪,单个arg版本对我有用...什么版本的Groovy?1.8.6? (2认同)