Skip to content

Instantly share code, notes, and snippets.

@abreslav
Last active December 16, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abreslav/5371492 to your computer and use it in GitHub Desktop.
Save abreslav/5371492 to your computer and use it in GitHub Desktop.
A question about getClass()
/*
* 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 { }
}
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