raf*_*ian 10 reflection groovy function introspection
我正在使用Groovy 1.8.4,试图得到封闭函数的名称......
def myFunction() {
println functionName??
}
Run Code Online (Sandbox Code Playgroud)
我试过delegate
,this
,owner
,Groovy的抱怨没有找到这样的对象.
我也试过Java hack new Exception().getStackTrace()[0].getMethodName()
,但那只是打印newInstance0
小智 16
groovy的StackTraceUtils.sanitize怎么样?这是一个简单的例子:
import org.codehaus.groovy.runtime.StackTraceUtils
class A {
def methodX() {
methodY()
}
def methodY() {
methodZ()
}
def methodZ() {
def marker = new Throwable()
StackTraceUtils.sanitize(marker).stackTrace.eachWithIndex { e, i ->
println "> $i ${e.toString().padRight(30)} ${e.methodName}"
}
}
}
new A().methodX()
Run Code Online (Sandbox Code Playgroud)
粘贴到独立脚本时,上面的输出test.groovy
如下:
$ groovy test.groovy
> 0 A.methodZ(test.groovy:13) methodZ
> 1 A.methodY(test.groovy:9) methodY
> 2 A.methodX(test.groovy:5) methodX
> 3 A$methodX.call(Unknown Source) call
> 4 test.run(test.groovy:21) run
Run Code Online (Sandbox Code Playgroud)
消毒方法从痕迹和清洁的痕迹中过滤掉所有常规的内部mumbo jumbo,...stackTrace.find { }
应该给你一个不错的开始.
Rob*_*Fey 12
import org.codehaus.groovy.runtime.StackTraceUtils
def getCurrentMethodName(){
def marker = new Throwable()
return StackTraceUtils.sanitize(marker).stackTrace[1].methodName
}
def helloFun(){
println( getCurrentMethodName() )
}
helloFun()
Run Code Online (Sandbox Code Playgroud)
输出:
helloFun
Run Code Online (Sandbox Code Playgroud)
您可以通过堆栈跟踪来获取它,我已经能够通过以下方式获取它:
groovy:000> def foo() { println Thread.currentThread().stackTrace[10].methodName }
===> true
groovy:000> foo()
foo
groovy:000> class Foo {
groovy:001> def bar() { println Thread.currentThread().stackTrace[10].methodName }
groovy:002> }
===> true
groovy:000> new Foo().bar()
bar
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7687 次 |
最近记录: |