from: http://javarevisited.blogspot.hk/2012/07/when-class-loading-initialization-java-example.html
Classloading and initialization in Java
Understanding of when a class is loaded and initialized in JVM is one of the fundamental concept of Java programming language. Thanks to Java language specification we have everything clearly documented and explained, but many Java programmer still doesn't know when a class is loaded or when a class is initialized in Java. Class loading and initialization seems confusing and complex to many beginners and its true until having some experience in belt its not always easy to get into subtle details of How JVM works in Java. In this Java tutorial we will see when class loading occurs in Java and when and how class and interface are initialized in Java. I will not go into detail of ClasLoader or How ClassLoader works in Java, that is subject of another post I am planning. just to keep this article focused and concise. There are several articles on Java fundamentals in Javarevisited like How HashMap works in Java and How Garbage collection works in Java. If you are interested you can also check those.
When Class is loaded in Java
Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.
When a Class is initialized in Java
After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :
1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.
Reflection can also cause initialization of class. Some methods of java.lang.reflect package may cause class to be initialized. JLS Strictly says that a class should not be initialized by any reason other than above.
How Class is initialized in Java
Now we know what triggers initialization of a class in Java, which is precisely documented in Java language specification. Its also important to know in which order various fields (static and non static), block (static an non static), various classes (sub class and super class) and various interfaces (sub interface, implementation class and super interface) is initialized in Java. Infact many Core Java interview question and SCJP question based on this concept because it affect final value of any variable if its initialized on multiple places. Here are some of the rules of class initialization in Java:
1) Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
2) Super Class is initialized before Sub Class or derived class in Java
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type of Sub Class, Sub Interface or by implementation class of interface.
4) interface initialization in Java doesn't cause super interfaces to be initialized.
5) static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.
6)non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.
Examples of class initialization in Java:
Here is an example of when class is initialized in Java. In this example we will see which classes are initialized in Java.
/**
* Java program to demonstrate class loading and initialization in Java.
*/
public class ClassInitializationTest {
public static void main(String args[]) throws InterruptedException {
NotUsed o = null; //this class is not used, should not be initialized
Child t = new Child(); //initializing sub class, should trigger super class initialization
System.out.println((Object)o == (Object)t);
}
}
/**
* Super class to demonstrate that Super class is loaded and initialized before Subclass.
*/
class Parent {
static { System.out.println("static block of Super class is initialized"); }
{System.out.println("non static blocks in super class is initialized");}
}
/**
* Java class which is not used in this program, consequently not loaded by JVM
*/
class NotUsed {
static { System.out.println("NotUsed Class is initialized "); }
}
/**
* Sub class of Parent, demonstrate when exactly sub class loading and initialization occurs.
*/
class Child extends Parent {
static { System.out.println("static block of Sub class is initialized in Java "); }
{System.out.println("non static blocks in sub class is initialized");}
}
Output:
static block of Super class is initialized
static block of Sub class is initialized in Java
non static blocks in super class is initialized
non static blocks in sub class is initialized
false
* Java program to demonstrate class loading and initialization in Java.
*/
public class ClassInitializationTest {
public static void main(String args[]) throws InterruptedException {
NotUsed o = null; //this class is not used, should not be initialized
Child t = new Child(); //initializing sub class, should trigger super class initialization
System.out.println((Object)o == (Object)t);
}
}
/**
* Super class to demonstrate that Super class is loaded and initialized before Subclass.
*/
class Parent {
static { System.out.println("static block of Super class is initialized"); }
{System.out.println("non static blocks in super class is initialized");}
}
/**
* Java class which is not used in this program, consequently not loaded by JVM
*/
class NotUsed {
static { System.out.println("NotUsed Class is initialized "); }
}
/**
* Sub class of Parent, demonstrate when exactly sub class loading and initialization occurs.
*/
class Child extends Parent {
static { System.out.println("static block of Sub class is initialized in Java "); }
{System.out.println("non static blocks in sub class is initialized");}
}
Output:
static block of Super class is initialized
static block of Sub class is initialized in Java
non static blocks in super class is initialized
non static blocks in sub class is initialized
false
Observation:
1) Super class is initialized before sub class in Java.
2) Static variables or blocks are initialized before non static blocks or fields.
3) Not used class is not initialized at all because its not been used, none of the cases mentioned on JLS or above which triggers initialization of class is not happened here.
Let's have a look on another example of class initialization in Java:
/**
* Another Java program example to demonstrate class initialization and loading in Java.
*/
public class ClassInitializationTest {
public static void main(String args[]) throws InterruptedException {
//accessing static field of Parent through child, should only initialize Parent
System.out.println(Child.familyName);
}
}
class Parent {
//compile time constant, accessing this will not trigger class initialization
//protected static final String familyName = "Lawson";
protected static String familyName = "Lawson";
static { System.out.println("static block of Super class is initialized"); }
{System.out.println("non static blocks in super class is initialized");}
}
Output:
static block of Super class is initialized
Lawson
* Another Java program example to demonstrate class initialization and loading in Java.
*/
public class ClassInitializationTest {
public static void main(String args[]) throws InterruptedException {
//accessing static field of Parent through child, should only initialize Parent
System.out.println(Child.familyName);
}
}
class Parent {
//compile time constant, accessing this will not trigger class initialization
//protected static final String familyName = "Lawson";
protected static String familyName = "Lawson";
static { System.out.println("static block of Super class is initialized"); }
{System.out.println("non static blocks in super class is initialized");}
}
Output:
static block of Super class is initialized
Lawson
Observation
1. Here class initialization occurs because static field is accessed which is not a compile time constant. had you declare "familyName" compile time constant using final keyword in Java (as shown in commented section) class initialization of super class would not have occurred.
2) Only super class is initialized even though static field is referenced using sub type.
There is another example of class initialization related to interface on JLS which explains clearly that initialization of sub interfaces does not trigger initialization of super interface. I highly recommend reading JLS 14.4 for understating class loading and initialization in more detail.
That's all on When a class is initialized and loaded in Java. We have seen clear guidelines form JLS regarding class initialization. We have also seen the order on which super type and sub type are initialized and order of initialization for both static and non static fields and blocks in Java.
相关推荐
Whenever a method is invoked a new stack frame is added to the stack and corresponding frame is removed when its execution is completed. Native method stack: holds the state of each native method ...
Last Loaded 任务4-4-16x16.pdsbak
Last Loaded 任务4-3-LED点阵式电子广告牌控制.pdsbak
常见的设置包括`-javaagent`参数,例如`-javaagent:path/to/springloaded-1.2.5.RELEASE.jar`,确保指定了正确的jar路径。 3. **启动应用**:配置完成后,启动你的Java应用。SpringLoaded会在后台运行,监听代码变更...
《Java调用Windows API:Jacob库的使用与异常处理》 在Java开发中,有时我们需要与Windows操作系统进行深度交互,例如操作Office文档、自动化任务等。这时,Java库Jacob(Java COM Bridge)就显得尤为重要。Jacob是...
基于PMPC-b-PBMA 嵌段共聚物的紫杉醇聚合物胶束的形态以及释放动力学研究,褚洪雨,刘娜,本文首先运用可逆加成-断裂链转移(RAFT)“活性”自由基聚合方法制备了不同聚(2-甲基丙烯酰氧乙基磷酰胆碱)(PMPC)含量...
这个压缩包文件"springloaded-1.2.8.RELEASE"包含了该工具的特定版本,即1.2.8.RELEASE。 **SpringLoader的原理** SpringLoaded的核心功能是类加载器(ClassLoader)的增强,它能够监测到源代码的变化,并在代码保存...
The plugins filters, when run or loaded into imagej, will allow user to be able to edit images and perform different operations on images. The user can build on the plugins to create edit an image ...
A nonlinear evaluation of a tubular adhesive scarf joint loaded in tension and in torsion
例如,在Eclipse中,可以在Run Configuration中选择Java Application,然后在JRE选项卡中添加`-javaagent:path/to/springloaded-x.x.x.jar`,替换为实际的jar路径。 - **命令行启动**:对于通过命令行启动的应用,...
springboot热部署的依赖包,手动安装到maven库中;还需要更改开发工具的配置,具体配置请自行查找
--loaded-class-count :应用程序运行时将加载的类数 --thread-count : 用户线程数 --jvm-options : JVM 选项,通常是JAVA_OPTS --head-room : 可用总内存的百分比,将保留未分配以覆盖 JVM 开销 内存计算器打印...
超临界二氧化碳流体技术制备载甲氨蝶呤的Fe3O4-PLLA-PEG-PLLA微球的磁靶向性能研究,唐娜,王士斌,通过超临界CO2强制分散悬浮液法制备(共沉淀(C)和微囊化(M))负载甲氨蝶呤的Fe 3O4-PLLA-PEG-PLLA磁性复合微球...
What is a Java Class File? What's in a Class File? Special Strings Fully Qualified Names Simple Names Descriptors The Constant Pool The CONSTANT_Utf8_info Table The CONSTANT_Integer_info Table...
System.out.println("Loaded and initialized class with custom ClassLoader: " + clazz.getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } ``` #### 六、总结 通过以上介绍,我们可以...
工作原理基于jdk代理方式,实现JVM的Instrumentation进行premain或agentmain代理加载以及TransformerManager的transform方法进行翻译,对增加的class进行listener,对已有class文件内容变化lastModified进行实时...
- You can communicate with loaded website through simple API (Javascript-Unity back and forth) - You can hide top bar (with title and back button) if you don't like it - You can specify browser's ...
Q492107 - A JPEG image loaded from a stream and then cloned by the TdxSmartImage.Clone method is incompletely painted by TdxSmartImage draw routines Q488736 - An AV occurs when closing an application ...
Q492107 - A JPEG image loaded from a stream and then cloned by the TdxSmartImage.Clone method is incompletely painted by TdxSmartImage draw routines Q488736 - An AV occurs when closing an application ...
-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> ...