Last active
December 16, 2015 03:39
-
-
Save abreslav/5371492 to your computer and use it in GitHub Desktop.
A question about getClass()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A question about Java (not Kotlin!), first asked by Alexander Udalov (@udalov). | |
* | |
* How many calls to getClass() does the code below make? | |
* Curiously enough, the answer is ONE (see the byte codes below). | |
* | |
* Now the questions is: why does javac emit the call to getClass()? | |
*/ | |
class C { | |
public static void main(String[] args) { | |
C c = new C(); | |
c.new D(); | |
} | |
class D { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static main([Ljava/lang/String;)V | |
L0 | |
LINENUMBER 147 L0 | |
NEW C | |
DUP | |
INVOKESPECIAL C.<init> ()V | |
ASTORE 1 | |
L1 | |
LINENUMBER 148 L1 | |
NEW C$D | |
DUP | |
ALOAD 1 | |
DUP | |
INVOKEVIRTUAL java/lang/Object.getClass ()Ljava/lang/Class; // <---- HERE IT IS! | |
POP | |
INVOKESPECIAL C$D.<init> (LC;)V | |
POP | |
L2 | |
LINENUMBER 149 L2 | |
RETURN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment