class file loading in Java is dynamic. JVM directives are encapsulated in the. class file, and the. class file loading process is dynamic, that is, when we use it to load, if not, we will not load our class. There are two different ways to use this. The first is when a new object (this time to pay special attention to, when the design to polymorphism, there will be a little change, the compiler will do some optimizations, so that when loading will be loaded in advance design to polymorphic classes, Here's an example (Example 1) to illustrate this point. The other is when the static code of a class is invoked.
 
java 代码
 //example 1
 // Zoo.java
 abstract class Animal {
 Animal(){
 System.out.println("Animal constructor");
 }
 }
 class Tiger extends Animal {
 Tiger(){
 System.out.println("Tig constructor ");
 }
 }
 class Dog extends Animal {
 Dog(){
 System.out.println("Dog Constructor ");
 }
 }
 public class Zoo {
 private Animal am; //Example 1.1
 //private Dog am; Example 1.2
 private Tiger tiger;
 Zoo(){
 tiger = new Tiger();
 am = new Dog();
 }
 public static void main(String [] args){
 System.out.println("new Zoo before");
 Zoo z = new Zoo();
 System.out.println("new Zoo after ");
 }
 }
 
When we comment out the example.1.1 row, run the Example1.2 line, and the result is as follows:
 
Example 1.2
 
By analyzing the results of the above two graphs, we can see that when we assign the subclass object to the parent class, the compiler does a little optimization, so the loader has loaded the parent class and the subclass (example1.1 result) when there is no new subclass object, and when there is no polymorphism, we can see that when the new Dog () will load the Dog and the parent class. In either way, before new, the class does have to be loaded into memory.
 
Java provides us with two kinds of dynamic mechanisms. The first is implicit mechanism. In fact, when the new object and the static method of invoking the class, the implicit mechanism is working. The second type is the display mechanism. There are two strategies to display (the first one is the Java.lang.Class forname (String str) method, and the second is Java.lang.ClassLoader loadclass ()).
 
The first: The use of forname method
 
When we look up API documents, we find that there are two forms of forname methods. were as follows:
 
public static Class<?> forName(String className)
 throws ClassNotFoundException
 public static Class<?> forName(String name,
 boolean initialize,
 ClassLoader loader)
 throws ClassNotFoundException