我可以使用 Java 反射获取方法参数名称吗? [英] Can I obtain method parameter name using Java reflection?
本文介绍了我可以使用 Java 反射获取方法参数名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的课程:
public class Whatever
{
public void aMethod(int aParam);
}
有没有办法知道aMethod
使用了一个名为aParam
的参数,它的类型是int
?
is there any way to know that aMethod
uses a parameter named aParam
, that is of type int
?
推荐答案
总结:
- 如果编译期间包含调试信息,
- 获取参数名称是可能的.请参阅此答案了解更多详情
- 否则不可能获取参数名称
- 可以使用
method.getParameterTypes()
获取参数类型
- getting parameter names is possible if debug information is included during compilation. See this answer for more details
- otherwise getting parameter names is not possible
- getting parameter type is possible, using
method.getParameterTypes()
为了为编辑器编写自动完成功能(如您在其中一条评论中所述),有几个选项:
For the sake of writing autocomplete functionality for an editor (as you stated in one of the comments) there are a few options:
- 使用
arg0
、arg1
、arg2
等 - 使用
intParam
、stringParam
、objectTypeParam
等 - 使用上述的组合 - 前者用于非原始类型,后者用于原始类型.
- 根本不显示参数名称 - 只显示类型.
这篇关于我可以使用 Java 反射获取方法参数名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文