I am trying to implement a subset of Java for an academic study. Well, I'm in the last stages (code generation) and I wrote a rather simple program to see how method arguments are handled:
class Main {
public static void main(String[] args) {
System.out.println(args.length);
}
}
Then I built it, and ran 'Main.class' through an online disassembler I found at:http://www.cs.cornell.edu/People/egs/kimera/disassembler.html
I get the following implementation for the 'main' method: (the disassembled output is in Jasmin)
.method public static main([Ljava/lang/String;)V
.limit locals 1
.limit stack 2
getstatic java/lang/System/out Ljava/io/PrintStream;
aload_0
arraylength
invokevirtual java/io/PrintStream.println(I)V
return
.end method
My problem with this is:
1. aload_0 is supposed to push 'this' on to the stack (thats what the JVM spec seems to say)
2. arraylength is supposed to return the length of the array whose reference is on the top-of-stack
So according to me the combination of 1 & 2 should not even work.
Answer
aload_0 is supposed to push 'this' on to the stack
Not quite … aload_0 reads the first argument of the method. In member functions, this happens to be the this reference. But main is not a member function, it’s a static function so there is no thisargument, and the true first argument of the method is args.
本文解释了Java中main方法的参数处理方式,特别是如何通过aload_0指令获取第一个参数,并澄清了它在静态方法中不指向this而是指向第一个实际参数。
1060

被折叠的 条评论
为什么被折叠?



