InJava. LangThere isClassloaderClass,ClassloaderThe basic goal is to provide services for class requests and dynamically load classes and resources as needed. Only when one class needs to be used(UseNewKeyword to instantiate a class)The Class Loader loads the class and initializes it.
One Java ApplicationProgramYou can use different types of class loaders. For example Web Application Server Medium, Servlet Using the developer-defined class loader, Java. Lang. String In use JVM System loader , Bootstrap Class LoaderOther classes defined by the developer are Appclassloader Load. In JVM The differences between the class name and the class loader are different. Java Type. Therefore, JVM Allow us to use different loaders to load the same Namespace Of Java Class, but in fact these are the same Namespace Of Java Classes can be completely different classes. This mechanism ensures JDK Built-in Java. Lang. String Is unique.
2.There are two ways to load a class:
(1)Implicit Mode
UseNewKeyword: Let the Class Loader load the required class as needed
(2)Explicit Mode
ByJava. Lang. ClassOfForname ()Method Loading
Public static class forname (string classname)
Public static class forname (string classname, Boolean initialize, classloader loader)
Parameter description:
Classname-Fully Qualified name of the required class
Initialize-Required class(StaticCodeBlock Initialization)
Loader-Class Loader used to load classes
Only one parameter is called.Forname () The method is equivalentClass. forname (classname, true, loader) .
These two methods must be connected to the native method at last. Forname0 () , Which is defined as follows:
Private Static native class forname0 (string name, Boolean initialize, classloader loader) throws classnotfoundexception;
Only one parameter Forname () Method. :
Forname0 (classname, true, classloader. getcallerclassloader ());
The three parameters Forname () , The last call is :
Forname0 (name, initialize, loader );
Therefore New To instantiate a class, or to use only one parameter Class. forname () Method, which is implicitly " Load class + Run static code blocks " . However Class. forname () Method,If the second parameter isFalseThe class loader will only load the class instead of initializing the static code block. The static code block will be initialized only when the class is instantiated.The static code block is initialized when the class is first instantiated.
Directly use the Class Loader
Obtains the class to which the object belongs.: Getclass ()Method
Get the class loader of this class: Getclassloader ()Method
3.RunJava XXX. ClassProcess
FindJRE-- FoundJVM. dll-- StartJVMAnd initialize it.Bootstrap loader-- LoadExtclassloader-- LoadAppclassloader-- ExecuteJava XXX. Class