问题
I have compiled the following code (Methods and variables are elided for brevity):
// Outer.java
public class Outer
{
private class Inner
{
}
void someMethod()
{
Inner inObj = this.new Inner();
}
public static void main(String s[])
{
Outer outerObj = new Outer();
}
}
When I listed the classes created, it displayed the following:
Outer$1.class
Outer$Inner.class
Outer.class
Outer and Outer$Inner appear logical. What is the purpose of Outer$1 class? What is the order of creation of these in time scale?
回答1:
Curious. I'm not sure what this is for. But if you decompile the classes, you can see how it is used:
public class Outer {
public Outer();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
void someMethod();
Code:
0: new #2 // class Outer$Inner
3: dup
4: aload_0
5: aconst_null
6: invokespecial #3 // Method Outer$Inner."<init>":(LOuter;LOuter$1;)V
9: astore_1
10: return
public static void main(java.lang.String[]);
Code:
0: new #4 // class Outer
3: dup
4: invokespecial #5 // Method "<init>":()V
7: astore_1
8: return
}
class Outer$Inner {
final Outer this$0;
Outer$Inner(Outer, Outer$1);
Code:
0: aload_0
1: aload_1
2: invokespecial #1 // Method "<init>":(LOuter;)V
5: return
}
class Outer$1 {
}
So, Outer$1
seems to contain nothing - not even a default constructor. But a reference to a Outer$1
has to be passed to Outer$Inner
to construct it. Mysteriously, the value passed in someMethod
is null
(line 5 in someMethod
).
来源:https://stackoverflow.com/questions/47589638/why-does-javac-create-an-additional-class