Think in Java Class Loading

Java类加载问题思考

1
2
3
public abstract class C {
static boolean flag = false;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public class A extends C {

static {
System.out.println("static A");
if (!flag) {
System.out.print("load from A");
D.load();
flag = true;
}
}


public A() {
System.out.println("constructor A");

}

@Override
public String toString() {
return "A{" + flag + "}";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class B extends C {

static {
System.out.println("static B");
if (!flag){
System.out.print("load from B");
D.load();
flag = true;
}
}

public B(){
System.out.println("constructor B");
}

@Override
public String toString() {
return "B{" + flag + "}";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class D {
static List<C> list = Lists.newArrayList();

static {
System.out.println("D 1 size=" + list.size() + ", " + list);
list.add(new A());
System.out.println("D 2 size=" + list.size() + ", " + list);
list.add(new B());
System.out.println("D 3 size=" + list.size() + ", " + list);

}


public static void load() {
System.out.println("loading>>>>>>>>>>" + " list=" + Arrays.deepToString(list.toArray()));

if (!C.flag) {
for (C s : list) {
System.out.println("loading.............." + s.getClass().getSimpleName() + " list=" + Arrays.deepToString(list.toArray()));
}
}
}

}
1
2
3
4
5
6
7
8
public class Test {

public static void main(String []ar){
A a = new A();
// B a = new B();

}
}