Getting the name of a method parameter

2020-01-24 05:55发布

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?

8条回答
淡お忘
2楼-- · 2020-01-24 06:21

In Java parameter names are not available via reflection.

查看更多
仙女界的扛把子
3楼-- · 2020-01-24 06:28

I have found another solution after marking this question as answered. The solution is Paranamer.

Example:

 Method method = Foo.class.getMethod(...);

 Paranamer paranamer = new CachingParanamer();

 String[] parameterNames = paranamer.lookupParameterNames(method) // throws ParameterNamesNotFoundException if not found

 // or ...

 parameterNames = paranamer.lookupParameterNames(method, false) // will return null if not found
查看更多
登录 后发表回答