前面是看到某个论坛讨论的内部类加载顺序的问题,链接如下:http://www.oschina.net/question/2273217_217864#tags_nav
今天看了单例模式,对内部类的加载顺序产生了疑问。所以来请教大家。
我们知道,java当中,类的加载顺序是:类静态块-类静态属性-类内部属性-类构造方法。
但是当有内部类的时候会怎样呢?我们先看一下代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public
class
Singleton {
public
static
class
Inner{
static
{
System.out.println(
"TestInner Static!"
);
}
public
final
static
Singleton testInstance =
new
Singleton(
3
);
}
public
static
Singleton getInstance(){
return
Inner.testInstance;
}
public
Singleton(
int
i ) {
System.out.println(
"Test "
+ i +
" Construct! "
);
}
//类静态块
static
{
System.out.println(
"Test Static"
);
}
//类静态属性
public
static
Singleton testOut =
new
Singleton(
1
);
public
static
void
main(String args[]){
Singleton t =
new
Singleton(
2
);
Singleton.getInstance();
}
}
|
1
2
3
4
5
|
Test Static
Test
1
Construct!
Test
2
Construct!
TestInner Static!
Test
3
Construct!
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public
class
Singleton {
public
static
class
Inner{
public
final
static
Singleton testInstance =
new
Singleton(
3
);
static
{
System.out.println(
"TestInner Static!"
);
}
}
public
static
Singleton getInstance(){
return
Inner.testInstance;
}
public
Singleton(
int
i ) {
System.out.println(
"Test "
+ i +
" Construct! "
);
}
//类静态块
static
{
System.out.println(
"Test Static"
);
}
//类静态属性
public
static
Singleton testOut =
new
Singleton(
1
);
public
static
void
main(String args[]){
Singleton t =
new
Singleton(
2
);
Singleton.getInstance();
}
}
|
输出为:
1
2
3
4
5
|
Test Static
Test
1
Construct!
Test
2
Construct!
Test
3
Construct!
TestInner Static!
|
是你的内部内final在捣乱,final static这种初始化会导致不一样,你把final去掉就不会发生,不过static在内部内的加载顺序跟类加载顺序不一样。