Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name of a method parameter

In Java 6, 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 slice2 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 getParameterTypes or getGenericParameterTypes.

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

like image 786
Tiago Veloso Avatar asked Jul 20 '11 09:07

Tiago Veloso


People also ask

Can I obtain method parameter name using Java reflection?

You can obtain the names of the formal parameters of any method or constructor with the method java. lang. reflect.

What method can be used to read parameter names?

Following is a generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order.

How get arguments name in Python?

To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions aMethod and foo.

What is a parameter name in Python?

Parameters are the input variables bounded by parentheses when defining a function, whereas arguments are the values assigned to these parameters when passed into a function (or method) during a function call.


1 Answers

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; it can be configured using the preferences: Java -> Compiler and then enable "Store information about method parameters (usable via reflection)" (see also this answer).

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.

like image 192
Bozho Avatar answered Sep 24 '22 00:09

Bozho