我在scala repl中使用:javap命令,并试图查看traits伴侣对象,但我似乎无法找到方法。这是我从命令行做的事情。
$ 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相同
答案 0 :(得分:2)
您不是在询问配套模块,而是询问特征实现类。
未找到类字节是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")
- 但也许这不是开玩笑。