Tiago Veloso Tiago Veloso - 2 years ago 88
Java Question

Getting the name of a method parameter

In Java6, imagine I have the following method signature:

public void makeSandwich(Bread slice1, Bread slice2, List<Filling> fillings, boolean mustard)

I would like to know, at runtime, the value that was passed on to
or any other parameter, the important bit here is that I want to get the value by parameter name.

I know how to get the list of parameter types with

Ideally I would like to get a list of parameter names instead of types. Is there a way to do so?

Answer Source

Parameter names are available if you have told the compiler to include them (compile with debug information). Spring has ParameterNameDiscoverer which can help you obtain the names. The default implementation uses asm ClassReader to do so.

With javac you should include the -g argument to include debug information. With eclipse I think it is there by default.

Some frameworks use this. For example spring-mvc has @RequestParam which defaults to the param name, if resolvable. It also supports explicit naming - @RequestParam("foo") in case no debug information is provided.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download