If I have a class like this:
public class Whatever
{
public void aMethod(int aParam);
}
is there any way to know that aMethod
uses a parameter named aParam
, that is of type int
?
If I have a class like this:
public class Whatever
{
public void aMethod(int aParam);
}
is there any way to know that aMethod
uses a parameter named aParam
, that is of type int
?
if you use the eclipse, see the bellow image to allow the compiler to store the information about method parameters
Yes.
Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option).
Then this code snippet should work:
see org.springframework.core.DefaultParameterNameDiscoverer class
While it is not possible (as others have illustrated), you could use an annotation to carry over the parameter name, and obtain that though reflection.
Not the cleanest solution, but it gets the job done. Some webservices actually do this to keep parameter names (ie: deploying WSs with glassfish).
The Paranamer library was created to solve this same problem.
It tries to determine method names in a few different ways. If the class was compiled with debugging it can extract the information by reading the bytecode of the class.
Another way is for it to inject a private static member into the bytecode of the class after it is compiled, but before it is placed in a jar. It then uses reflection to extract this information from the class at runtime.
https://github.com/paul-hammant/paranamer
I had problems using this library, but I did get it working in the end. I'm hoping to report the problems to the maintainer.
Parameter names are only useful to the compiler. When the compiler generates a class file, the parameter names are not included - a method's argument list only consists of the number and types of its arguments. So it would be impossible to retrieve the parameter name using reflection (as tagged in your question) - it doesn't exist anywhere.
However, if the use of reflection is not a hard requirement, you can retrieve this information directly from the source code (assuming you have it).