Рассмотрим следующий фрагмент: (Я сталкивался с этим синтаксисом при проверке некоторых декомпилированных файлов классов, и это минимальное представление)
public class Main {
public static void main(String[] args) {
Main.Inner o = new Main().new Inner() {};
System.out.println("Bye from " + o.getClass());
}
class Inner {}
}
Это компилируется и работает нормально (я тестировал кучу JDK). Может кто-нибудь объяснить, как получается эта компиляция и что представляет этот код?
Этот код создает 3 класса:
1. Main - This creates the following code (I removed the irrelevant parts):
new Main$1
dup
new Main
dup
invokespecial Method Main <init> ()V
dup
invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
pop
invokespecial Method Main$1 <init> (LMain;)V
Why is it calling getClass (the result is popped anyway)?
2. Main$Inner - This class looks like as would expect an inner class to look
3. Main$1 - This creates the following class (I removed the irrelevant parts):
final class Main$1 extends Main$Inner
method <init> : (LMain;)V
aload_0
aload_1
dup
invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
pop
invokespecial Method Main$Inner <init> (LMain;)V
return
Again, why is it calling getClass (the result is popped anyway)?
Кстати, он может быть вложен еще дальше как это:
public class Main {
public static void main(String[] args) {
Object o = new Main().new Inner1().new Inner2().new Inner3() {};
System.out.println("Bye from " + o.getClass());
}
class Inner1 {
class Inner2 {
class Inner3 {
}
}
}
}