How is the java "this" keyword implemented?

How does the this pointer point to the object itself? Is this a java implementation or a compiler implementation?

+6
source share
3 answers

Well, if you're interested, why not look at the byte code generated by the compiler

 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(); } 

}

Compile with

% JAVA_HOME% / bin / javac HelloWorld.java

Get bytecode with

javap -c HelloWorld

change add output

 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 

}

+1
source

In the JVM bytecode, the local variable 0 (basically register 0) points to the current object when the method is called. The compiler simply uses this as an alias for local variable 0.

So, I think the answer is that the compiler implements this .

+7
source

Sounds like a philosophical question. I am not sure what the Java implementation is.

this defined in JLS and is a keyword in Java, and compilation must comply with this standard. If you have a method like

 object.method(args) 

what is actually being called in bytecode is a method that looks like

 method(object, args); 

where this is the first argument.

At the JVM level, parameters have no names, and the JIT can optimize the argument if it is not actually used.

+3
source

Source: https://habr.com/ru/post/906391/


All Articles