【问题标题】:Get Parameter list of a closure dynamically in Groovy在 Groovy 中动态获取闭包的参数列表
【发布时间】:2017-11-13 13:55:38
【问题描述】:

我在一个用shell.evaluate() 方法加载的groovy 文件中定义了一个闭包。 我需要通过使用shell."$closurename".call(arguments) 调用调用程序来调用这个闭包。 但是,要制定闭包参数(上面的参数),我现在需要知道闭包 $Closurename 接受的参数和参数名称是什么。有没有办法在 Groovy 中动态地知道这一点?我签入了 metaClass.method 属性,但这在下面的示例中不起作用。

下面是示例代码。

        def arguments;
        shell.evaluate(new File("/tmp/myGroovyClosureFile.groovy"))
        testBlock = "myClosureName"
        //Code here to find the parameters for myClosureName and create
        //the arguments variable
        shell."$testBlock".call(arguments)

【问题讨论】:

    标签: groovy metaprogramming groovyshell


    【解决方案1】:

    正如 Jeff 所提到的,在为闭包生成代码时以某种方式匿名化参数名称似乎很时髦。但是,您仍然可以使用反射来获取尽可能多的信息:

    def cl = { int a, String b ->
    println(a)
    println(b)
    }
    
    def callMethod = cl.class.methods.find {
        it.name == "call"
    }
    
    println callMethod.parameterTypes
    println callMethod.parameters.name
    

    和输出:

    [int, class java.lang.String]
    [arg0, arg1]
    

    【讨论】:

      【解决方案2】:

      有没有办法在 Groovy 中动态了解这一点?

      你不能真正在运行时动态地做到这一点。

      【讨论】:

      • 在 java 中,您可以使用反射 api 来获取此信息。 groovy 闭包是否有等价物?
      • 仅供参考...“在 java 中,您可以使用反射 api 来获取此信息” - 如果您指的是字节码中的参数名称,那是正确的。如果您指的是源代码中的参数名称,我认为这是不正确的,除非该类是在启用调试符号的情况下编译的。
      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2016-09-29
      • 2014-03-15
      相关资源
      最近更新 更多