如何在 Scala/Java 方法中通过反射获取参数名称和类型?
我们可以使用反射来获取方法名称,如下所示:
object Foo { def bar(name:String, age:Int) = {} }
val foo = Foo.getClass
val methods = foo.getMethods.filter(_.getName.startsWith("b"))
methods.foreach(m => println(m.getName))
我现在需要获取参数类型和名称。
- 参数名称是否存储在字节码中?如果答案是肯定的,如何访问它们?
- 如果上面的答案是否定的,我们可以使用注释以某种方式存储名称吗?
- 有人可以举个例子来阅读这些类型以及如何使用它们。我只对具有
String
和/或Array[String]
类型参数的函数感兴趣。
[编辑:] Java 版本的解决方案也可以。
[编辑:]注释似乎是一种方法。然而,Scala 注释支持并不是那么好。 相关问题。
We can use reflection to get method names as follows:
object Foo { def bar(name:String, age:Int) = {} }
val foo = Foo.getClass
val methods = foo.getMethods.filter(_.getName.startsWith("b"))
methods.foreach(m => println(m.getName))
I now need to get the parameter types and names.
- Are the parameter names stored in the byte-code? If answer is yes, how to access them?
- If answer above is no, can we store the names somehow using annotations?
- Can someone given an example to read the types, and how to use them. I am interested only in functions having
String
and/orArray[String]
type parameters.
[EDIT:] Java version of the solution also ok.
[EDIT:] Annotations seems to be one way to do it. However, Scala annotation support is not that good. Related SO question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我还没有尝试过,但 http://paranamer.codehaus.org/ 是为此任务而设计的。
I've not tried it, but http://paranamer.codehaus.org/ is designed for this task.
Java 的字节码规范不要求存储参数名称。但是,它们可以通过调试符号潜入(如果编译器被告知生成它们)。我知道 ASM 字节码库会读取这些符号(如果存在)。请参阅我对“如何获取对象构造函数的参数名称” 查找构造函数参数名称的 Java 示例(在字节码中,构造函数只是名称为
)。Java's bytecode specification doesn't require the parameter names to be stored. However, they can sneak in via the debugging symbols (if the compiler was told to generate them). I know that the ASM bytecode library reads these symbols if they are present. See my answer to "How to get the parameter names of an object's constructors" for a Java example of finding constructor parameter names (in bytecode, constructors are just methods whose name is
<init>
).如果类中存在调试信息,则可以按如下方式完成。
我基本上使用 Adam Paynter 的回答 并复制粘贴 此处稍作编辑后让它在 Scala 中工作。
If debugging info is present in the classes, it can be done as follows.
I am basically using Adam Paynter's answer and copy-pasting the code from here after slight edit to get it to work in Scala.