2021-03-04 16:15:04 -07:00
|
|
|
// reflection/ClassInitialization.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
class Initable {
|
2016-11-21 12:37:57 -08:00
|
|
|
static final int STATIC_FINAL = 47;
|
|
|
|
static final int STATIC_FINAL2 =
|
2015-06-15 17:47:35 -07:00
|
|
|
ClassInitialization.rand.nextInt(1000);
|
|
|
|
static {
|
|
|
|
System.out.println("Initializing Initable");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Initable2 {
|
|
|
|
static int staticNonFinal = 147;
|
|
|
|
static {
|
|
|
|
System.out.println("Initializing Initable2");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Initable3 {
|
|
|
|
static int staticNonFinal = 74;
|
|
|
|
static {
|
|
|
|
System.out.println("Initializing Initable3");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class ClassInitialization {
|
|
|
|
public static Random rand = new Random(47);
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
2015-06-15 17:47:35 -07:00
|
|
|
Class initable = Initable.class;
|
|
|
|
System.out.println("After creating Initable ref");
|
|
|
|
// Does not trigger initialization:
|
2016-11-21 12:37:57 -08:00
|
|
|
System.out.println(Initable.STATIC_FINAL);
|
2021-01-31 15:42:31 -07:00
|
|
|
// Triggers initialization:
|
2016-11-21 12:37:57 -08:00
|
|
|
System.out.println(Initable.STATIC_FINAL2);
|
2021-01-31 15:42:31 -07:00
|
|
|
// Triggers initialization:
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(Initable2.staticNonFinal);
|
|
|
|
Class initable3 = Class.forName("Initable3");
|
|
|
|
System.out.println("After creating Initable3 ref");
|
|
|
|
System.out.println(Initable3.staticNonFinal);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
After creating Initable ref
|
|
|
|
47
|
|
|
|
Initializing Initable
|
|
|
|
258
|
|
|
|
Initializing Initable2
|
|
|
|
147
|
|
|
|
Initializing Initable3
|
|
|
|
After creating Initable3 ref
|
|
|
|
74
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|