In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the core knowledge points of ClassLoader in Java". In daily operation, I believe many people have doubts about the core knowledge points of ClassLoader in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "what are the core knowledge points of ClassLoader in Java?" Next, please follow the editor to study!
The role of JDK and JRE
JDK provides a programming environment for java, which includes environment functions for compilation and debugging, including JRE (JRE in the JDK directory is a private JRE, while JRE installed in the same directory as JDK is a public JRE). Development generally runs the JDK dedicated JRE, while external programs generally run the public JRE, realizing that the jre with different division of labor is responsible for the content of their respective scope.
JRE provides a necessary environment platform for JAVA programs to run.
JAVAHOME 、 PATH 、 CLASSPATH
JAVAHOME: the location path of the JDK installation, such as: d:\ Program Files\ Java\ jdk1.8.0_241
PATH: running commands in bin after configuration does not require completion of the path. For example, you can run java and javac commands at any location,% JAVA_HOME%\ bin
CLASSPATH: points to the jar package path% JAVA_HOME%\ lib
Types of class loaders
There are three types of ClassLoader in JVM:
Bootstrap ClassLoader startup class (or root class) loader
Class loader for Extention ClassLoader extension
Appclass Loader application class loader
(1) Bootstrap ClassLoader
The top-level class loader of Bootstrap ClassLoader mainly loads rt.jar, resources.jar, charsets.jar and class files under the core class library% JRE_HOME%\ lib.
/ / execute System.out.println (System.getProperty ("sun.boot.class.path")); / / output result D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ resources.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ rt.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ sunrsasign.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ jsse.jar D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ jce.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ charsets.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ jfr.jar; D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ classes
(2) Extention ClassLoader
Extention ClassLoader extended classloader, which mainly loads jar packages and class files in the% JRE_HOME%\ lib\ ext directory.
/ / execute System.out.println (System.getProperty ("java.ext.dirs")); / / output D:\ Program Files\ Java\ jdk1.8.0_241\ jre\ lib\ ext;C:\ Windows\ Sun\ Java\ lib\ ext
(3) Appclass Loader
Appclass Loader, also known as SystemAppClass, loads all classes of the currently applied classpath.
Execution order of class loader
In addition to the startup class loader (Bootstrap ClassLoader), both the extension class loader and the application class loader are initialized by the class sun.misc.Launcher, while the Launcher class is loaded by the startup class loader. The codes related to Launcher are as follows:
Public Launcher () {Launcher.ExtClassLoader var1; try {/ / initializes the extended classloader. The constructor has no input parameters and cannot get the startup classloader var1 = Launcher.ExtClassLoader.getExtClassLoader ();} catch (IOException var10) {throw new InternalError ("Could not create extension class loader", var10) } try {/ / initialize the application classloader. The input parameters are extended classloader this.loader = Launcher.AppClassLoader.getAppClassLoader (var1);} catch (IOException var9) {throw new InternalError ("Could not create application class loader", var9);} / / set the context classloader Thread.currentThread (). SetContextClassLoader (this.loader); / /.}
Loading order: Bootstrap CLassloder > Extention ClassLoader > AppClassLoader
Parent loader concept
Both AppClassLoader and ExtClassLoader inherit URLClassLoader. Each classloader has a parent loader (note: parent and parent loaders are two different concepts), which can be obtained through getParent ().
System.out.println ("ClassLoader is:" + cl.toString ()); System.out.println ("ClassLoader\'s parent is:" + cl.getParent () .toString ()); System.out.println ("ClassLoader\'s grand father is:" + cl.getParent () .getParent () .toString ()
AppClassLoader's parent loader is ExtClassLoader
The parent loader of ExtClassLoader is Bootstrap ClassLoader (the above code outputs that ExtClassLoader is null because Bootstrap ClassLoader itself is not a Java class)
Bootstrap ClassLoader is written by Bootstrap Cure +, which is itself part of the virtual machine, so it is not a JAVA class, that is, it cannot get its reference in the java code. When JVM starts, it loads the class file in the core jar package, such as rt.jar, through the rt.jar class loader, which loads the previous int.class,String.class. Then, as we analyzed earlier, JVM initializes sun.misc.Launcher and creates Extension ClassLoader and AppClassLoader instances. And set ExtClassLoader as the parent loader of AppClassLoader. Bootstrap does not have a parent loader, but it can act as a parent loader for ClassLoader.
Parental appointment
Parent delegation model: when a class loader receives a class load request, it will first request its parent class loader to load, recursively, and when the parent class loader cannot find the class (based on the fully qualified name of the class), the subclass loader will try to load.
Time sequence diagram
Why use the parent delegation model?
The parent delegation model is designed to ensure the type safety of the Java core library. All Java applications need to reference at least the java.lang.Object class, which needs to be loaded into the Java virtual machine at run time. If the loading process is done by a custom class loader, there may be multiple versions of java.lang.Object classes that are not compatible with each other.
Through the parent delegation model, the loading of the class of the Java core library is completed by starting the class loader, which ensures that the classes used by Java applications are the same version of the Java core library and are compatible with each other.
Custom class loader
Whether it's Bootstrap ClassLoader, ExtClassLoader, etc., these classloaders simply load jar packages or resources in the specified directory. If we need to load dynamically, such as loading a class file from a specified directory, this can be done through a custom class loader.
The custom class loader simply inherits the java.lang.ClassLoader class and then overrides the findClass (String name) method, which indicates how to get the byte stream of the class. If you want to break the parent delegation specification, you also need to rewrite the loadClass method (the concrete logical implementation of the parent delegation). But it is not recommended.
Public class ClassLoaderTest extends ClassLoader {private String classPath; public ClassLoaderTest (String classPath) {this.classPath = classPath } / * write the logic of the findClass method * * @ param name * @ return * @ throws ClassNotFoundException * / @ Override protected Class findClass (String name) throws ClassNotFoundException {/ / get the class file byte array byte [] classData = getClassData (name); if (classData = = null) {throw new ClassNotFoundException () } else {/ / generate class object return defineClass (name, classData, 0, classData.length) }} / * write logic * * @ param className * @ return * / private byte [] getClassData (String className) {/ / read the bytes of class files String path = classNameToPath (className); try {InputStream is = new FileInputStream (path) ByteArrayOutputStream stream = new ByteArrayOutputStream (); byte [] buffer = new byte [2048]; int num = 0; / read the bytecode while ((num = is.read (buffer))! =-1) {stream.write (buffer, 0, num);} return stream.toByteArray () } catch (IOException e) {e.printStackTrace ();} return null The full path to the class file * * @ param className * @ return * / private String classNameToPath (String className) {return classPath + File.separatorChar + className.replace ('., File.separatorChar) + ".class" } public static void main (String [] args) {String classPath = "/ Users/zzs/my/article/projects/java-stream/src/main/java/"; ClassLoaderTest loader = new ClassLoaderTest (classPath); try {/ / load the specified class file Class object1 = loader.loadClass ("com.secbro2.classload.SubClass") System.out.println (object1.newInstance (). ToString ());} catch (Exception e) {e.printStackTrace ();} at this point, the study of "what are the core knowledge points of ClassLoader in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.