Is it possible to get method parameter names in scala

As far as I know, we cannot do this in Java. Can we do this in scala?

Suppose the following method exists:

def insert(name:String, age:Int) {
    // insert new user
}

Can I get the parameter names nameand agein scala?


UPDATE

I want to do this because I want to bind method parameters automatically.

For example, this is a web application, it has some actions defined as:

class UsersController extends Controller {
    def create(name: String, age: Int) {
          // insert the user
    }
}

The client clicked the submitform button creating the user. The URL will be /users/createwith some send options.

On the server side, when we get the url with the name /users/create, we will find the method createin the controller UsersControllerfound now. Then I need to get the parameter names of this method, then we can get their values:

val params = getParamsFromRequest()
val method = findMethodFromUrl("/users/create")
val paramNames = getParamNamesOfMethod(method)
val paramValues = getValues(params, paramNames)

// then invoke
method.invoke(controller, paramValues)

, ?

+3
3

, :

import scalaj.reflect._
for {
  clazz <- Mirror.ofClass[UsersController].toSeq
  method <- clazz.allDefs.find(_.name == "insert").toSeq
  params <- method.flatParams
} yield params

toSeqs, , Option .

, , . , , , :)

UPDATE

... , , , , github.

( String):

import scalaj.reflect._
for {
  clazz <- Option(Class forName "x.y.UsersController")
  mirror <- Mirror.ofClass(clazz).toSeq
  method <- mirror.allDefs.find(_.name == "insert").toSeq
  params <- method.flatParams
} yield params
+8

, Java: Java?

+2

Why not just use different method names (to reflect parameters that can be passed)? For example craeteWithNameAndAgeAndGender(a fairly standard approach). You can never have multiple methods with the same name (/ arity / parameter types and order) and just different parameter names - method overloading does not work this way.

+1
source

Source: https://habr.com/ru/post/1796247/


All Articles