Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static initialization block & class loader

 
Yi Meng
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know that static initialization block will be executed when the class is loaded, but how do we judge whether a class is loaded or not? does it depend on whether there is an object of that class created, or just a reference of that class during the runtime?
and also when is it loaded? only when instantiation of the class occurs?
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is some information related to your question extracted from The Java Virtual Machine by Bill Venners Ch 7 The Lifetime of a Type
The Java virtual machine specification gives implementations flexibility in the timing of class and interface loading and linking, but strictly defines the timing of initialization. All implementations must initialize each class or interface on its first active use. The following six situations qualify as active uses:
1. A new instance of a class is created (in bytecodes, the execution of a new instruction. Alternatively, via implicit creation, reflection, cloning, or deserialization.)
2. The invocation of a static method declared by a class (in bytecodes, the execution of an invokestatic instruction)
3. The use or assignment of a static field declared by a class or interface, except for static fields that are final and initialized by a compile-time constant expression (in bytecodes, the execution of a getstatic or putstatic instruction)
4. The invocation of certain reflective methods in the Java API, such as methods in class Class or in classes in the java.lang.reflect package
5. The initialization of a subclass of a class (Initialization of a class requires prior initialization of its superclass.)
6. The designation of a class as the initial class (with the main()< method) when a Java virtual machine starts up
Class loaders (bootstrap or user-defined) need not wait until a type's first active use before they load the type. Class loaders are allowed to cache binary representations of types, load types early in anticipation of eventual use, or load types together in related groups.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic