Landy
Landy

Reputation: 47

Can Scala reflect static method?

I have a java library, and I'd like to call some static functions from the library by Scala using reflection. I tried to use the java way that I created URLClassloader and reflected the method by getDeclaredMethod(), but it seems not working in Scala. And I was thinking about the Scala way, but it seems no method or field can be reflected without a specific instance is created. So is it possible to reflect static method in Scala? And if it is, what's the proper way to do?

Sorry, I think I made a mistake, it works fine with the java api. Thanks guy..

Upvotes: 4

Views: 1932

Answers (2)

Daniel Martin
Daniel Martin

Reputation: 23548

I just solved this, after finding this question in my search, so to save people who also find this question by Googling:

If you have a scala TypeTag or WeakTypeTag, it is in fact possible to get the java.lang.Class object for the underlying java class, and from there you can use the java reflection API to do what you want to do:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> val wt = weakTypeTag[java.text.DateFormat]
wt: reflect.runtime.universe.WeakTypeTag[java.text.DateFormat] = TypeTag[java.text.DateFormat]

scala> val clazz = wt.mirror.runtimeClass(wt.tpe)
clazz: Class[_] = class java.text.DateFormat

scala> val fld = clazz.getDeclaredField("SHORT")
fld: java.lang.reflect.Field = public static final int java.text.DateFormat.SHORT

scala> val meth = clazz.getDeclaredMethod("getTimeInstance", fld.getType)
meth: java.lang.reflect.Method = public static final java.text.DateFormat java.text.DateFormat.getTimeInstance(int)

scala> val methResult = meth.invoke(null, fld.get(null))
methResult: Object = java.text.SimpleDateFormat@b4dc7db3

scala> methResult.asInstanceOf[java.text.Format].format(System.currentTimeMillis)
res28: String = 9:15 AM

Hat tip to the accepted answer on this question which pointed me in the right direction.

Note that scala methods on companion objects are a whole different kettle of fish. This different SO question might help you with that.

Upvotes: 3

Eugene Burmako
Eugene Burmako

Reputation: 13048

If you referring to the functionality of Scala's native runtime reflection API provided in scala-reflect.jar, then the answer is two-fold:

  1. It is possible to invoke "static" methods written in Scala (i.e. methods defined in objects).
  2. It is not possible to invoke static methods written in Java (here's an issue for that: https://issues.scala-lang.org/browse/SI-6459).

Upvotes: 2

Related Questions