在Groovy中查找方法的名称 [英] Find out a method's name in Groovy

查看:210
本文介绍了在Groovy中查找方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Groovy中找到被调用方法的名称吗?

$ b println这种方法称为方法+ methodName
}

与鸭打字会允许非常简洁(可能难以阅读)的代码。

解决方案

不,与Java一样,没有本地这样做的方式。

您可以编写AST转换,以便您可以注释该方法,并且可以在该方法内设置局部变量。



或者你可以使用Java的老式方法来生成stackTrace,并找到正确的StackTraceElement,如下所示:

  import static org.codehaus.groovy.runtime.StackTraceUtils.sanitize 
$ b $ def myMethod(){
def name = sanitize(new Exception()。fillInStackTrace() ).stackTrace.find {
!(it.className ==〜/^java_.*|^org.codehaus.*/)
} ?. methodN ame
$ b println在方法$ name


myMethod()


Is there a way in Groovy to find out the name of the called method?

def myMethod() {
    println "This method is called method " + methodName
}

This, in combination with duck typing would allow for quite concise (and probably hard to read) code.

解决方案

No, as with Java there's no native way of doing this.

You could write an AST transform so that you could annotate the method and this could set a local variable inside the method.

Or you can do it the good old Java way of generating a stackTrace, and finding the correct StackTraceElement with something like:

import static org.codehaus.groovy.runtime.StackTraceUtils.sanitize

def myMethod() {
  def name = sanitize( new Exception().fillInStackTrace() ).stackTrace.find {
    !( it.className ==~ /^java_.*|^org.codehaus.*/ )
  }?.methodName

  println "In method $name"
}

myMethod()

这篇关于在Groovy中查找方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆