tribbloid
tribbloid

Reputation: 3838

What's the easiest way to convert a Scala reflection MethodSymbol/MethodSignature to a Java Method?

Scala reflection is designed for both compilation time and run time. So it can identify polymorphic method more effectively than Java (see my previous post In Scala Reflection, How to get generic type parameter of a concrete subclass?), which suffers from type erasure.

However, this method can only be invoked using Scala reflection's mirror, which is slightly slower than its java counterpart, I would like to know if there is an easy way to convert Scala MethodSymbol, which is returned by Type.members:

import import scala.reflect.runtime.universe._

val tpe = typeTag[String].tpe
val methodSymbol = tpe.method("size": Name)

or MethodSignature, which is returned by Type.member.SignatureIn(Type):

val methodSignature = methodSymbol.typeSignatureIn(tpe)

to a Java method that can be directly invoked through Java reflection API:

val size = method.invoke("abc")
size: Int = 3

Is it possible?

Upvotes: 2

Views: 465

Answers (1)

pyrospade
pyrospade

Reputation: 8078

Here's one way to simulate Java-style invocation.

object ScalaMethodUtil {

  import scala.reflect.runtime.universe._

  def invoke(m: MethodSymbol)(o: Any)(args: Any*): Any = {
    val mirror = runtimeMirror(o.getClass.getClassLoader).reflect(o)
    mirror.reflectMethod(m)(args: _*)
  }
}

Upvotes: 1

Related Questions