2011-08-17 16 views
2

例如,我定义了一个方法:什么语言可以让我们获得定义的参数名称和传递的参数名称?

def hello(String name) { 
    println("Hello " + name) 
} 

我想参数的名称在运行时:

def hello(String name) { 
    println("The name of the parameter of this method is: " + getParamName()) 
    // getParamName() will be `name` here 
} 

而且,我希望得到的参数通过名称:

def hello(String name) { 
    println("Passed parameter name: " + getPassedName()) 
} 

String user1 = "someone" 
hello(user1) 

它会打印:

Passed parameter name: user1 

注意,这里是user1,变量名!

我知道这很难,因为java/groovy/scala不能这样做。但我认为这是一个非常有用的功能(特别是对于网页框架设计)。有语言可以做到吗?

+1

你可以这样做C#,看看这里的例子:http://stackoverflow.com/questions/869610/c-resolving-a-parameter-name-at-runtime – openshac

+0

D被说成有编译实时反思!你可能会看到他们的文档http://dlang.org/traits.html – nawfal

回答

4

不能在一般得到一个说法的名称,因为参数可能不是一个命名的变量。鉴于这种:

def hello(String name) { 
    println("Passed parameter name: " + getPassedName()) 
} 

会是什么输出这里:

hello("a literal") 
hello("an " + "expression") 

鉴于此,有一些语言,让你访问传递的参数的原始AST。 Lisp,Io和Ioke中的宏都可以让你定义一些函数,这些函数将大量未经评估的代码作为参数,然后可以检查它们。

+0

'user1'你是对的,我从来没有想过这个 – Freewind

3
  • 的Python

还有就是inspect module和的许多功能也将让你的函数的参数名称和默认值之一。

inspect.getargspec(func) 
  • C#

下面是另一个很好的例子SO质疑使用匿名类型和反射Resolving a parameter name at runtime

  • 的Javascript

而这里的一个办法做到这一点在Javascript中使用RegEx(ano疗法SO问题,也提到了Python的方式)Inspect the names/values of arguments in the definition/execution of a JavaScript function

+0

谢谢,但我们可以得到**通过**变量名吗?在我的问题 – Freewind