[英]Java - When is the 0th local variable not 'this'?
In the local variables of a Java method, when will the 0th local variable not refer to 'this'? 在Java方法的局部变量中,第0个局部变量何时不会引用'this'?
I can think of static methods as a counterexample, are there any others? 我可以将静态方法看作反例,还有其他方法吗?
UPDATE: I am referring to bytecode 更新:我指的是字节码
The JVM specification section 2.6.1 seems to think that it only depends on whether it's a static (class) method or an instance method: JVM规范部分2.6.1似乎认为它只取决于它是静态(类)方法还是实例方法:
The Java Virtual Machine uses local variables to pass parameters on method invocation.
Java虚拟机使用局部变量在方法调用上传递参数。 On class method invocation, any parameters are passed in consecutive local variables starting from local variable 0. On instance method invocation, local variable 0 is always used to pass a reference to the object on which the instance method is being invoked (this in the Java programming language).
在类方法调用中,任何参数都在从局部变量0开始的连续局部变量中传递。在实例方法调用中,局部变量0总是用于传递对调用实例方法的对象的引用(这在Java中)编程语言)。 Any parameters are subsequently passed in consecutive local variables starting from local variable 1.
随后,任何参数都在从局部变量1开始的连续局部变量中传递。
That's in terms of the initial values of the local variables; 这是局部变量的初始值; see Mike Strobel's answer for an example where it's explicitly changed during the method.
请参阅Mike Strobel的答案,了解在该方法中明确更改的示例。
There are two cases I am aware of when local #0 does not refer to this
: 有两种情况我知道的地方时,#0指的不是
this
:
The second case is perfectly valid. 第二种情况完全有效。 Local #0 is only guaranteed to reference
this
upon entry to an instance method. 本地#0仅保证在进入实例方法时引用
this
。 Within the method, there is nothing inherently "special" about slot #0; 在该方法中,关于时隙#0没有任何固有的“特殊”; it may be (re)written like any other slot (as can those used by formal parameters).
它可以(重新)写成任何其他插槽(正式参数使用的那些插槽)。 Consider the following example in Jasmin format:
请考虑以下Jasmin格式的示例:
.class public HelloWorld
.super java/lang/Object
.method public <init>()V
.limit stack 2
aload_0
invokenonvirtual java/lang/Object/<init>()V
ldc "Hello World."
astore_0
getstatic java/lang/System/out Ljava/io/PrintStream;
aload_0
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
return
.end method
.method public static main([Ljava/lang/String;)V
.limit stack 2
new HelloWorld
invokenonvirtual HelloWorld/<init>()V
return
.end method
In HelloWorld/<init>()V
, we overwrite local #0 with a constant string. 在
HelloWorld/<init>()V
,我们用常量字符串覆盖本地#0。 Thus, the second use of aload_0
loads a value other than a this
pointer. 因此,第二次使用
aload_0
会加载除this
指针之外的值。 It is not unusual for the same local slot to refer to different "conceptual" variables at different points in the code, especially if a class has been run through a bytecode optimizer. 同一个局部槽在代码中的不同点引用不同的“概念”变量并不罕见,特别是如果一个类已经通过字节码优化器运行。
So, in answer to your question: yes, there is at least one other counterexample. 所以,回答你的问题:是的,至少还有一个反例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.