Can I obtain method parameter name using Java refl

2019-01-01 01:06发布

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?

14条回答
孤独寂梦人
2楼-- · 2019-01-01 01:18

if you use the eclipse, see the bellow image to allow the compiler to store the information about method parameters

enter image description here

查看更多
呛了眼睛熬了心
3楼-- · 2019-01-01 01:19

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:

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   for (Parameter p : m.getParameters()) {
    System.err.println("  " + p.getName());
   }
}
查看更多
梦醉为红颜
4楼-- · 2019-01-01 01:19

see org.springframework.core.DefaultParameterNameDiscoverer class

DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] params = discoverer.getParameterNames(MathUtils.class.getMethod("isPrime", Integer.class));
查看更多
浪荡孟婆
5楼-- · 2019-01-01 01:22

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).

查看更多
若你有天会懂
6楼-- · 2019-01-01 01:23

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.

查看更多
低头抚发
7楼-- · 2019-01-01 01:23

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).

查看更多
登录 后发表回答