2

For example, I defined a method:

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

I want to the the name of argument in runtime:

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

And, I expect to get the passed name of the parameter:

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

String user1 = "someone"
hello(user1)

It will print:

Passed parameter name:  user1

Notice, here is user1, the variable name!

I know this is difficult, since java/groovy/scala can't do it. But I think it's a very useful feature(especially for web-framework design). Is there a language can do it?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    You can do it C#, have a look over here for an example: http://stackoverflow.com/questions/869610/c-resolving-a-parameter-name-at-runtime – openshac Aug 17 '11 at 09:27
  • D is said to have compile time reflection! You may see their documentation http://dlang.org/traits.html – nawfal Feb 06 '13 at 10:12

2 Answers2

4

You can't get the name of an argument in general because the argument may not be a named variable. Given this:

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

What would it output here:

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

Given that, there are some languages that let you access the raw AST of the passed argument. Macros in Lisp, Io, and Ioke all let you define functions that will take a chunk of unevaluated code as the argument, which you can then inspect.

munificent
  • 11,946
  • 2
  • 38
  • 55
3
  • Python

There is the inspect module and one of the many functions there will get you the name and default value of arguments of a function.

inspect.getargspec(func)
  • C#

Here's a good example from another SO question using anonymous types and reflection Resolving a parameter name at runtime

  • Javascript

And here's a way to do it in Javascript using RegEx (another SO question, that also mentions the Python way) Inspect the names/values of arguments in the definition/execution of a JavaScript function

Community
  • 1
  • 1
Peter Kelly
  • 14,253
  • 6
  • 54
  • 63