如何实现java"this"关键字?

mav*_*rav 6 java

this指针如何指向对象本身?它是java实现还是编译器实现?

Ern*_*ill 7

在JVM字节码中,当调用方法时,局部变量0(基本上是寄存器0)指向当前对象.编译器只是this用作局部变量0的别名.

所以我猜答案是编译器实现的this.


Sha*_*der 1

好吧,如果您有兴趣,为什么不看看编译器生成的字节码

class HelloWorld
{
   private String hello = "Hello world!";

   private void printHello(){
   System.out.println (this.hello);
}

public static void main (String args[]){
  HelloWorld hello = new HelloWorld();
  hello.printHello();
}
Run Code Online (Sandbox Code Playgroud)

}

编译使用

%JAVA_HOME%/bin/javac HelloWorld.java

使用获取字节码

javap -c 你好世界

编辑添加输出

enter code here

 HelloWorld();
 Code:
 0:   aload_0
 1:   invokespecial   #1; //Method java/lang/Object."<init>":()
 4:   aload_0
 5:   ldc     #2; //String Hello world!
 7:   putfield        #3; //Field hello:Ljava/lang/String;
 10:  return

 public static void main(java.lang.String[]);
 Code:
 0:   new     #6; //class HelloWorld
 3:   dup
 4:   invokespecial   #7; //Method "<init>":()V
 7:   astore_1
 8:   aload_1
 9:   invokespecial   #8; //Method printHello:()V
12:  return
Run Code Online (Sandbox Code Playgroud)

}