In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about the principle of java class loader. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
First, loading, linking and initialization of Java class
1, load: find and load the binary data of the class
The binary byte stream that defines the class is obtained through the fully qualified name of a class. The static storage structure represented by the byte stream is transformed into the run-time data structure of the method area. A java.lang.Class class object representing the class is generated in memory as an access entry for all kinds of data of the class in the method area.
2, Link
Verify:
Ensure the correctness of the loaded class
Prepare:
Allocate memory for static variables of the class and initialize them to default values
Parsing:
Convert symbolic references in a class to direct references
3, initialize
Assign the correct initial value to the static variable of the class
Second, the main ways for JVM to load classes
Download .class files directly from the local system and download .class files from archived files such as zip,jar. Class files are extracted from proprietary databases. Java source files are dynamically compiled to .class.
Third, the types and functions of JVM loading classes
JVM uses CLassLoader (class loader) to dynamically load a class file into memory. ClassLoader is divided into the following four categories:
1, Bootstrap class loader
This kind of loader does not have a parent loader, it is responsible for loading the core class libraries of the virtual machine, such as java.lang.*, etc. The root class loader loads the class library from the directory specified by the system property sun.boot.class.path. The implementation of the classloader depends on that the underlying operating system is part of the virtual machine implementation, which does not inherit the java.lang.ClassLoader class.
2, extended (Extension) class loader
Its parent class loader is the root class loader. It loads the class library from the directory specified by the java.ext.dirs system properties, or from the jrelibextsubdirectory of the JDK installation directory (the extension directory loads the class library), and how the user-created JAR asks you to put in this directory will also be automatically loaded by the extension class loader. The extension class loader is a pure Java class and is a subclass of the java.lang.ClassLoader class.
3, system class loader
Also known as the application class loader, its parent is the extended class loader. He loads the class from the directory specified by the environment variable classpath or the system property java.class.path, which is the default parent loader for the user-defined classloader. The system class loader is a pure Java class and is a subclass of the java.lang.ClassLoader class. In addition to the loader that comes with the above virtual machine, users can also inherit the java.lang.ClassLoader class to implement a custom loader.
Fourth, the principle of class loader
1. Introduction of the principle
ClassLoader uses the parent delegate model to search for classes, and each ClassLoader instance has a reference to the parent class loader (not an inherited relationship, but an inclusive relationship). The virtual machine built-in class loader (Bootstrap ClassLoader) does not have a parent class loader itself, but can be used as a parent class loader for other ClassLoader instances. When a ClassLoader instance needs to load a class, it will attempt to search for a class itself before delegating the task to its parent class loader. The process is checked from top to bottom. First, the top-most class loader, Bootstrap ClassLoader, attempts to load. If it is not loaded, the task is transferred to Extension ClassLoader to attempt to load. If it is not loaded, it is handed over to App ClassLoader for loading, if it does not load either. Is returned to the initiator of the delegate to load the class into a URL such as the specified file system or network. If none of them are loaded into this class, a ClassNotFoundException exception is thrown. Otherwise, the found class generates a definition of the class, loads it into memory, and finally returns the Class instance object of the class in memory.
2. The reasons for using the parental commission model
Because this avoids repeated loading, there is no need for the child ClassLoader to load again when the father has already loaded the class. For security reasons, let's imagine that if we don't use this delegation mode, we can use a custom String to dynamically replace the types defined in the java core api at any time, which has a great security risk, which can be avoided by parental delegation, because String is already loaded by the boot class loader (Bootstrcp ClassLoader) at startup. So a user-defined ClassLoader can never load a self-written String unless you change the default algorithm for the ClassLoader search class in JDK.
3. How to judge that two class are the same
When determining whether two class are the same, JVM determines not only whether the two class names are the same, but also whether they are loaded by the same class loader instance. JVM considers the two class to be the same only if both are satisfied. Even if two class are the same class bytecode, JVM will think that they are two different class if they are loaded by two different ClassLoader instances. For example, a Java class on the network org.classloader.simple.NetClassLoaderSimple,javac compiles and generates bytecode files NetClassLoaderSimple.class,ClassLoaderA and ClassLoaderB, which are two class loaders and reads the NetClassLoaderSimple.class file, and defines java.lang.Class instances to represent this class. For JVM, they are two different instance objects, but they are indeed the same bytecode file. If you try to generate a specific object for conversion from this Class instance, The runtime exception java.lang.ClassCaseException is thrown, indicating that these are two different types.
4. Common methods
(1) loadClass method
ClassLoader.loadClass () is the entry point for ClassLoader. This method is defined as follows:
Class loadClass (String name,boolean resolve)
Name is the name of the loaded class, and resolve tells the method that it is not necessary to resolve the class PS: not all classes need to be resolved. If JVM only wants to know whether the class exists or finds out the superclass of the class, then there is no need to resolve the class.
(2) defineClass method
The defineClass method takes an array of raw bytes and converts it to an object of Class. The original array contains data, such as mounted from a file system or network. DefineClass manages many complex implementation aspects of JVM-it parses bytecode into run-time data structures, validation, and so on, and cannot be overridden because the defineClass method is marked as final.
(3) findSytemClass method
The findSystemClass method is to find the local class Class file and load the
(4) resolveClass method
When we call and write our own loadClass method, we can call the resolveClass method to get the resolve parameter
(5) findLoadedClass method
You can call the change method before calling the loadClass method to see if the local ClassLoader has loaded the class, so that you can avoid reloading the class
(6) findClass method
This new method is called by default in the loadClass implementation. The purpose of findClass contains all the special code of classLoader without having to copy other code
(7) getSystemClassLoader method
If you override findClass or loadClass,getSystemClassLoader, you can access the system ClassLoader as the actual ClassLoader object (instead of calling it regularly from findSystemClass). To delegate the class request to the parent class ClassLoader, this new method allows ClassLoader to get its parent class ClassLoader. This method can be used when a custom ClassLoader cannot find a class using a special method.
The parent class ClassLoader is defined as the ClassLoader of the object that creates the code that the ClassLoader contains.
(8) forName method
There is a static method forName in the Class class, which has the same purpose as the loaderClass method in ClassLoader, which is used to load Class, but there is a difference in function:
LoadClass loading is actually loading without interpreting the class, so the class is not initialized. The forName method of the Class class, by contrast, interprets and initializes the Class when it is loaded with forName
Fifth, the use of class loaders
Use URLClassLoader to load classes
Import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader
Public class ClassLoaderTest {public static void main (String args []) {try {URL url = new URL ("file:/C:/Users/spark/Desktop/logs-analyzer.jar"); URLClassLoader myClassLoader1 = new URLClassLoader (new URL [] {url}, Thread.currentThread () .getContextClassLoader ()); Class clazz = myClassLoader1.loadClassQ ("study.ClassLoaderTest.TestAction") Method mainClass = clazz.getMethod ("action"); Constructor constructor = clazz.getConstructor (); Object obj = constructor.newInstance (); System.out.println (mainClass.invoke (obj));} catch (Exception e) {e.printStackTrace ();}
First define a class and then package it into jar
Public class TestAction {public String action () {return "this ActionTest class";}}
Sixth, a brief introduction of URLClassLoader in Spark
The class loader that Spark uses most internally is URLClassloader.
Private [spark] class MutableURLClassLoader (urls: Array [URL], parent: ClassLoader) extends URLClassLoader (urls, parent) {
Override def addURL (url: URL): Unit = {super.addURL (url)}
Override def getURLs (): Array [URL] = {super.getURLs ()}
}
This depends on the nature of Spark distributed computing, which will be discussed in more detail when it comes to the runtime environment in a later source series.
Thank you for reading! This is the end of this article on "what is the principle of java class loader". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.