Scala - 获取函数名称 [英] Scala - get function name

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

问题描述

我有一个函数 foo,它接受另一个函数(比如 bar)作为参数.有没有办法把bar的函数名作为foo里面的字符串获取?

I have a function foo which takes another function (say bar) as a parameter. Is there a way to get the function name of bar as a string inside foo?

推荐答案

没有.请参阅方法和函数之间的区别.方法不会作为参数在后台传递 - 当传递给其他方法/函数时,它们会扩展为函数对象.这些函数对象是匿名的、编译器生成的类的实例,并且没有名称(或者,至少是匿名类,具有一些可以使用反射访问但可能不需要的损坏名称).

No. See the difference between methods and functions. Methods aren't passed as parameters under the hood - they are expanded into function objects when being passed to some other method/function. These function objects are instances of anonymous, compiler-generated classes , and have no name (or, at least, being anonymous classes, have some mangled name which you could access using reflection, but probably don't need).

所以,当你这样做时:

def foo() {}

def bar(f: () => Unit) {}

bar(foo)

最后一次调用中实际发生的是:

what actually happens in the last call is:

bar(() => foo())

不过,理论上,您可以找到正在传递的函数对象所包装的方法的名称.你可以做字节码自省,分析上面方法bar中函数对象fapply方法体,并据此得出结论该方法的名称是.然而,这既是近似值又是矫枉过正.

Theoretically, though, you could find the name of the method that the function object you're being passed is wrapping. You could do bytecode introspection to analyze the body of the apply method of the function object f in method bar above, and conclude based on that what the name of the method is. This is both an approximation and an overkill, however.

这篇关于Scala - 获取函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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