Does Scala have introspection capable of something similar to Python's dir()?

无人久伴 提交于 2019-11-30 01:48:03
Thomas Jung

Scala does not have a reflection API. The only way to access this information is to use the Java reflection API. This has the disadvantage that the structure may change as the way Scala is represented in Java classes and interfaces may change in the future.

scala> classOf[AnyRef].getMethods
res0: Array[java.lang.reflect.Method] = Array(public final void ...

Some specific type information that is present in the byte code can be accessed with the ScalaSigParser.

import tools.scalap.scalax.rules.scalasig._
import scala.runtime._

val scalaSig = ScalaSigParser.parse(classOf[RichDouble])

That's one of my main uses for REPL. Type the object's name, dot, and then TAB and it will show all available methods.

It isn't perfect. For one thing, it shows protected methods, which won't be available unless you are extending the class. For another thing, it doesn't show methods available through implicit conversion.

And, of course, the IDEs are all capable of doing that.

You might want something like the following which would give you what you need. In this case, it operates on a String, obviously.

val testStr = "Panda"
testStr.getClass.getMethods.foreach(println)

Does that work?

You may want to use this little helper to beef up the REPL

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!