开发者

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

Yes, I know it's considered lazy by the non-Pythonistas. The reason I ask is that documentation is still woefully lacking in many Scala libraries (e.g. Scala-dbc, but that's not all I'm looking at), and if I could see the attributes 开发者_如何学Cof an object/class at runtime, I could at least figure out what's available. Thanks.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜