我正在 scala repl 中使用 :javap 命令,并试图查看特征伴随对象,但我似乎无法找出如何操作。这是我从命令行执行的操作。
$ cat > Foo.scala <<EOF
trait Foo {
def foo: String
def echo = println(foo)
}
EOF
$ scalac Foo.scala
$ javap Foo.class
Compiled from "Foo.scala"
public abstract class Foo$class {
public static void echo(Foo);
public static void $init$(Foo);
}
$ javap Foo\$class.class
Compiled from "Foo.scala"
public abstract class Foo$class {
public static void echo(Foo);
public static void $init$(Foo);
}
我在 repl 中尝试相同的操作并得到以下结果(使用 Bar 因为 Foo 将在 . 中编译,因此 repl 将拾取它)
scala> trait Bar {
| def bar: String
| def echo = println(bar)
| }
defined trait Bar
scala> :javap Bar
Compiled from "<console>"
public interface Bar{
public abstract java.lang.String bar();
public abstract void echo();
}
scala> :javap Bar$class
Failed: Could not find class bytes for 'Bar$class'
Scala 版本的 repl
$ scala -version
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
在 Mac 上运行
编辑: 刚刚下载了 scala 2.11 并在那里运行了 repl。似乎 :javap 能够获取该类,但它运行的是 :javap -v 而不是 :javap。切换到 :javap -p 使此输出与 2.10 相同
最佳答案
您不是在询问配套模块,而是在询问特征实现类。
找不到类字节是 2.10 中的一个错误,已在 2.11 中修复。
如果您确实有伴生对象,当前您必须使用其编码名称,例如 Bar$
。
scala> :pa
// Entering paste mode (ctrl-D to finish)
trait Bar { def bar: Int }
object Bar { def apply() = new Bar { def bar = 8 } }
// Exiting paste mode, now interpreting.
defined trait Bar
defined object Bar
scala> :javap -prv Bar$
Binary file Bar$ contains $line3.$read$$iw$$iw$Bar$
Size 701 bytes
MD5 checksum a46d3c3cb62cb5ed3521a697023e82dd
Compiled from "<console>"
public class $line3.$read$$iw$$iw$Bar$
[snip]
对于您的 impl 类示例,我认为您要求:
scala> :javap -public x.Foo$class
Compiled from "x.scala"
public abstract class x.Foo$class {
public static void echo(x.Foo);
public static void $init$(x.Foo);
}
注意:
scala> :javap -help
usage :javap [opts] [path or class or -]...
-help Prints this help message
-raw Don't unmangle REPL names
-app Show the DelayedInit body of Apps
-fun Show anonfuns for class or Class#method
-verbose/-v Stack size, number of locals, method args
-private/-p Private classes and members
-package Package-private classes and members
-protected Protected classes and members
-public Public classes and members
-l Line and local variable tables
-c Disassembled code
-s Internal type signatures
-sysinfo System info of class
-constants Static final constants
和
val DefaultOptions = List("-protected", "-verbose")
帮助菜单可以详细说明如何使用术语 Bar
而不是类型;可能会有一个即将推出的 -demo
显示各种用法。
我本打算使用反射 API 来开玩笑 - :javap TermName("Bar")
- 但也许这不是一个笑话。
关于scala - 无法使用scala的repl :javap to look at trait companion object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347640/