关于java内部类加载顺序的问题

前面是看到某个论坛讨论的内部类加载顺序的问题,链接如下: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!



但是,当我把内部类Inner的内部静态块和内部静态属性 testInstance 互换位置后,如下: 
?
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在内部内的加载顺序跟类加载顺序不一样。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我还要去追逐我的梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值