Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parameter names and types via reflection in Scala/Java methods?

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/or Array[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.

like image 347
Jus12 Avatar asked Oct 03 '11 21:10

Jus12


People also ask

Which method is used to fetch the parameter types using method parameter reflection?

reflect package is used to fetch the parameter types using method parameter reflection. Reflection is a process of analyzing and modifying all capabilities of class at runtime.

How to use reflection in Scala?

Types obtained through reflection can be instantiated by invoking their constructor using an appropriate “invoker” mirror (mirrors are expanded upon below). Let's walk through an example using the REPL: scala> case class Person(name: String) defined class Person scala> val m = ru. runtimeMirror(getClass.

What method can be used to read parameter names?

getName() returns the parameter names. If -parameters compiler argument has not been used, getName() method will return parameter name as arg0, arg1 etc.


1 Answers

I've not tried it, but http://paranamer.codehaus.org/ is designed for this task.

like image 145
Duncan McGregor Avatar answered Sep 28 '22 02:09

Duncan McGregor