คลาส Loaders ใน Java

1. ความรู้เบื้องต้นเกี่ยวกับ Class Loaders

ตัวโหลดคลาสมีหน้าที่โหลดคลาส Java ระหว่างรันไทม์แบบไดนามิกไปยัง JVM (Java Virtual Machine) นอกจากนี้ยังเป็นส่วนหนึ่งของ JRE (Java Runtime Environment) ดังนั้น JVM จึงไม่จำเป็นต้องรู้เกี่ยวกับไฟล์หรือระบบไฟล์พื้นฐานเพื่อรันโปรแกรม Java ด้วยคลาสโหลดเดอร์

นอกจากนี้คลาส Java เหล่านี้จะไม่ถูกโหลดลงในหน่วยความจำทั้งหมดในครั้งเดียว แต่เมื่อต้องการโดยแอปพลิเคชัน นี่คือที่ที่รถตักคลาสเข้ามาในภาพ มีหน้าที่โหลดคลาสลงในหน่วยความจำ

ในบทช่วยสอนนี้เราจะพูดถึงรถตักในตัวประเภทต่างๆวิธีการทำงานและการแนะนำการใช้งานที่กำหนดเองของเราเอง

2. ประเภทของรถตักในตัว

เริ่มต้นด้วยการเรียนรู้วิธีการโหลดคลาสต่างๆโดยใช้ตัวโหลดคลาสต่างๆโดยใช้ตัวอย่างง่ายๆ:

public void printClassLoaders() throws ClassNotFoundException { System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader()); System.out.println("Classloader of Logging:" + Logging.class.getClassLoader()); System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader()); }

เมื่อดำเนินการวิธีการข้างต้นจะพิมพ์:

Class loader of this class:[email protected] Class loader of Logging:[email protected] Class loader of ArrayList:null

อย่างที่เราเห็นมีรถตักชั้นเรียนที่แตกต่างกันสามแบบที่นี่ แอปพลิเคชันส่วนขยายและ bootstrap (แสดงเป็นค่าว่าง )

ตัวโหลดคลาสของแอ็พพลิเคชันจะโหลดคลาสที่มีเมธอดตัวอย่าง แอปพลิเคชันหรือตัวโหลดคลาสของระบบจะโหลดไฟล์ของเราเองใน classpath

ถัดไปส่วนขยายจะโหลดคลาสLogging ตัวโหลดคลาสส่วนขยายจะโหลดคลาสที่เป็นส่วนขยายของคลาส Java หลักมาตรฐาน

ในที่สุด bootstrap ก็โหลดคลาสArrayList bootstrap หรือ primordial class loader เป็นพาเรนต์ของตัวโหลดอื่น ๆ ทั้งหมด

อย่างไรก็ตามเราจะเห็นว่าผลลัพธ์สุดท้ายสำหรับArrayListนั้นจะแสดงค่าว่างในเอาต์พุต เนื่องจากตัวโหลดคลาส bootstrap เขียนด้วยโค้ดเนทีฟไม่ใช่ Java - ดังนั้นจึงไม่แสดงเป็นคลาส Java ด้วยเหตุนี้ลักษณะการทำงานของตัวโหลดคลาส bootstrap จะแตกต่างกันไปตาม JVM

ตอนนี้เรามาพูดถึงรายละเอียดเพิ่มเติมเกี่ยวกับรถตักแต่ละคลาสเหล่านี้

2.1. Bootstrap คลาส Loader

เรียน Java จะถูกโหลดโดยตัวอย่างของjava.lang.Classloader อย่างไรก็ตามตัวโหลดคลาสเป็นคลาสตัวเอง ดังนั้นคำถามคือใครโหลดjava.lang.ClassLoaderเอง?

นี่คือที่ที่ bootstrap หรือตัวโหลดคลาส primordial เข้ามาในรูปภาพ

มันเป็นหลักรับผิดชอบในการเรียนภายในโหลด JDK โดยทั่วไปrt.jarและห้องสมุดหลักอื่น ๆ ที่ตั้งอยู่ใน$ JAVA_HOME / JRE / lib ไดเรกทอรี นอกจากนี้ตัวโหลดคลาส Bootstrap ยังทำหน้าที่เป็นพาเรนต์ของอินสแตนซ์ClassLoaderอื่น ๆทั้งหมด

ตัวโหลดคลาส bootstrap นี้เป็นส่วนหนึ่งของ Core JVM และเขียนด้วยโค้ดเนทีฟตามที่ระบุไว้ในตัวอย่างข้างต้น แพลตฟอร์มที่แตกต่างกันอาจมีการใช้งานตัวโหลดคลาสนี้ที่แตกต่างกัน

2.2. ตัวโหลดคลาสส่วนขยาย

ตัวโหลดคลาสส่วนขยายเป็นลูกของตัวโหลดคลาส bootstrap และดูแลการโหลดส่วนขยายของคลาส Java หลักมาตรฐานเพื่อให้สามารถใช้ได้กับแอปพลิเคชันทั้งหมดที่ทำงานบนแพลตฟอร์ม

ตัวโหลดคลาสส่วนขยายโหลดจากไดเร็กทอรีส่วนขยาย JDK โดยปกติจะเป็นไดเร็กทอรี$ JAVA_HOME / lib / extหรือไดเร็กทอรีอื่น ๆ ที่กล่าวถึงในคุณสมบัติระบบjava.ext.dirs

2.3. ตัวโหลดคลาสของระบบ

ในทางกลับกันตัวโหลดคลาสของระบบหรือแอ็พพลิเคชันจะดูแลการโหลดคลาสระดับแอปพลิเคชันทั้งหมดลงใน JVM มันโหลดไฟล์ที่พบในตัวแปรสภาพแวดล้อม classpath ที่-classpathหรือ-cpคำสั่งตัวเลือกบรรทัด นอกจากนี้ยังเป็นลูกของคลาสตัวโหลดส่วนขยาย

3. Class Loaders ทำงานอย่างไร?

ตัวโหลดคลาสเป็นส่วนหนึ่งของ Java Runtime Environment เมื่อ JVM ร้องขอคลาสตัวโหลดคลาสจะพยายามค้นหาคลาสและโหลดนิยามคลาสลงในรันไทม์โดยใช้ชื่อคลาสแบบเต็ม

java.lang.ClassLoader.loadClass ()วิธีการเป็นผู้รับผิดชอบสำหรับการโหลดการกำหนดระดับลงรันไทม์ พยายามโหลดคลาสตามชื่อแบบเต็ม

ถ้าคลาสยังไม่ได้โหลดคลาสจะมอบหมายการร้องขอไปยังตัวโหลดคลาสพาเรนต์ กระบวนการนี้เกิดขึ้นซ้ำ ๆ

ในที่สุดถ้าตัวโหลดคลาสพาเรนต์ไม่พบคลาสคลาสลูกจะเรียกใช้เมธอดjava.net.URLClassLoader.findClass ()เพื่อค้นหาคลาสในระบบไฟล์เอง

ถ้าตัวโหลดคลาสลูกตัวสุดท้ายไม่สามารถโหลดคลาสได้มันจะพ่นjava.lang.NoClassDefFoundErrorหรือjava.lang.ClassNotFoundException

ลองดูตัวอย่างของเอาต์พุตเมื่อ ClassNotFoundException ถูกโยน

java.lang.ClassNotFoundException: com.baeldung.classloader.SampleClassLoader at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348)

ถ้าเราทำตามลำดับเหตุการณ์ได้ทันทีจากการเรียกjava.lang.Class.forName ()เราจะเข้าใจได้ว่าก่อนอื่นพยายามโหลดคลาสผ่านตัวโหลดคลาสแม่จากนั้นjava.net.URLClassLoader.findClass ()เพื่อค้นหา ชั้นเรียนเอง

เมื่อยังไม่พบคลาสมันจะพ่นClassNotFoundException

มีคุณสมบัติที่สำคัญสามประการของรถตักคลาส

3.1. รูปแบบการมอบหมาย

ตัวโหลดคลาสเป็นไปตามรูปแบบการมอบหมายเมื่อมีการร้องขอเพื่อค้นหาคลาสหรือทรัพยากรอินสแตนซ์ClassLoaderจะมอบหมายการค้นหาคลาสหรือทรัพยากรให้กับตัวโหลดคลาสพาเรนต์

สมมติว่าเรามีคำขอให้โหลดคลาสแอปพลิเคชันลงใน JVM ตัวโหลดคลาสของระบบก่อนจะมอบหมายการโหลดของคลาสนั้นไปยังตัวโหลดคลาสส่วนขยายพาเรนต์ซึ่งจะมอบสิทธิ์ให้กับคลาส bootstrap

เฉพาะในกรณีที่ bootstrap และตัวโหลดคลาสส่วนขยายไม่สำเร็จในการโหลดคลาสตัวโหลดคลาสระบบจะพยายามโหลดคลาสเอง

3.2. คลาสเฉพาะ

อันเป็นผลมาจากรูปแบบการมอบหมายจึงเป็นเรื่องง่ายที่จะสร้างความมั่นใจให้กับชั้นเรียนที่ไม่ซ้ำกันเนื่องจากเราพยายามมอบหมายให้สูงขึ้นเสมอ

หากตัวโหลดคลาสพาเรนต์ไม่สามารถค้นหาคลาสได้อินสแตนซ์ปัจจุบันจะพยายามทำเช่นนั้นเอง

3.3. ทัศนวิสัย

นอกจากนี้รถตักเด็กชั้นสามารถมองเห็นได้จากการเรียนโหลดโดยรถตักของระดับผู้ปกครอง

For instance, classes loaded by the system class loader have visibility into classes loaded by the extension and Bootstrap class loaders but not vice-versa.

To illustrate this, if Class A is loaded by an application class loader and class B is loaded by the extensions class loader, then both A and B classes are visible as far as other classes loaded by Application class loader are concerned.

Class B, nonetheless, is the only class visible as far as other classes loaded by the extension class loader are concerned.

4. Custom ClassLoader

The built-in class loader would suffice in most of the cases where the files are already in the file system.

However, in scenarios where we need to load classes out of the local hard drive or a network, we may need to make use of custom class loaders.

In this section, we'll cover some other uses cases for custom class loaders and we'll demonstrate how to create one.

4.1. Custom Class Loaders Use-Cases

Custom class loaders are helpful for more than just loading the class during runtime, a few use cases might include:

  1. Helping in modifying the existing bytecode, e.g. weaving agents
  2. Creating classes dynamically suited to the user's needs. e.g in JDBC, switching between different driver implementations is done through dynamic class loading.
  3. Implementing a class versioning mechanism while loading different bytecodes for classes with same names and packages. This can be done either through URL class loader (load jars via URLs) or custom class loaders.

There are more concrete examples where custom class loaders might come in handy.

Browsers, for instance, use a custom class loader to load executable content from a website. A browser can load applets from different web pages using separate class loaders. The applet viewer which is used to run applets contains a ClassLoader that accesses a website on a remote server instead of looking in the local file system.

And then loads the raw bytecode files via HTTP, and turns them into classes inside the JVM. Even if these applets have the same name, they are considered as different components if loaded by different class loaders.

Now that we understand why custom class loaders are relevant, let's implement a subclass of ClassLoader to extend and summarise the functionality of how the JVM loads classes.

4.2. Creating Our Custom Class Loader

For illustration purposes, let's say we need to load classes from a file using a custom class loader.

We need to extend the ClassLoader class and override the findClass() method:

public class CustomClassLoader extends ClassLoader { @Override public Class findClass(String name) throws ClassNotFoundException { byte[] b = loadClassFromFile(name); return defineClass(name, b, 0, b.length); } private byte[] loadClassFromFile(String fileName) { InputStream inputStream = getClass().getClassLoader().getResourceAsStream( fileName.replace('.', File.separatorChar) + ".class"); byte[] buffer; ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int nextValue = 0; try { while ( (nextValue = inputStream.read()) != -1 ) { byteStream.write(nextValue); } } catch (IOException e) { e.printStackTrace(); } buffer = byteStream.toByteArray(); return buffer; } }

In the above example, we defined a custom class loader that extends the default class loader and loads a byte array from the specified file.

5. Understanding java.lang.ClassLoader

Let's discuss a few essential methods from the java.lang.ClassLoader class to get a clearer picture of how it works.

5.1. The loadClass() Method

public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {

This method is responsible for loading the class given a name parameter. The name parameter refers to the fully qualified class name.

The Java Virtual Machine invokes loadClass() method to resolve class references setting resolve to true. However, it isn't always necessary to resolve a class. If we only need to determine if the class exists or not, then resolve parameter is set to false.

This method serves as an entry point for the class loader.

We can try to understand the internal working of the loadClass() method from the source code of java.lang.ClassLoader:

protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { long t0 = System.nanoTime(); try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } }

The default implementation of the method searches for classes in the following order:

  1. Invokes the findLoadedClass(String) method to see if the class is already loaded.
  2. Invokes the loadClass(String) method on the parent class loader.
  3. Invoke the findClass(String) method to find the class.

5.2. The defineClass() Method

protected final Class defineClass( String name, byte[] b, int off, int len) throws ClassFormatError

This method is responsible for the conversion of an array of bytes into an instance of a class. And before we use the class, we need to resolve it.

In case data didn't contain a valid class, it throws a ClassFormatError.

Also, we can't override this method since it's marked as final.

5.3. The findClass() Method

protected Class findClass( String name) throws ClassNotFoundException

This method finds the class with the fully qualified name as a parameter. We need to override this method in custom class loader implementations that follow the delegation model for loading classes.

Also, loadClass() invokes this method if the parent class loader couldn't find the requested class.

The default implementation throws a ClassNotFoundException if no parent of the class loader finds the class.

5.4. The getParent() Method

public final ClassLoader getParent()

This method returns the parent class loader for delegation.

Some implementations like the one seen before in Section 2. use null to represent the bootstrap class loader.

5.5. The getResource() Method

public URL getResource(String name)

This method tries to find a resource with the given name.

It will first delegate to the parent class loader for the resource. If the parent is null, the path of the class loader built into the virtual machine is searched.

If that fails, then the method will invoke findResource(String) to find the resource. The resource name specified as an input can be relative or absolute to the classpath.

It returns an URL object for reading the resource, or null if the resource could not be found or if the invoker doesn't have adequate privileges to return the resource.

It's important to note that Java loads resources from the classpath.

Finally, resource loading in Java is considered location-independent as it doesn't matter where the code is running as long as the environment is set to find the resources.

6. Context Classloaders

In general, context class loaders provide an alternative method to the class-loading delegation scheme introduced in J2SE.

Like we've learned before, classloaders in a JVM follow a hierarchical model such that every class loader has a single parent with the exception of the bootstrap class loader.

However, sometimes when JVM core classes need to dynamically load classes or resources provided by application developers, we might encounter a problem.

For example, in JNDI the core functionality is implemented by bootstrap classes in rt.jar. But these JNDI classes may load JNDI providers implemented by independent vendors (deployed in the application classpath). This scenario calls for the bootstrap class loader (parent class loader) to load a class visible to application loader (child class loader).

J2SE delegation doesn't work here and to get around this problem, we need to find alternative ways of class loading. And it can be achieved using thread context loaders.

The java.lang.Thread class has a method getContextClassLoader() that returns the ContextClassLoader for the particular thread. The ContextClassLoader is provided by the creator of the thread when loading resources and classes.

If the value isn't set, then it defaults to the class loader context of the parent thread.

7. Conclusion

Class loaders are essential to execute a Java program. We've provided a good introduction as part of this article.

เราได้พูดถึงรถตักประเภทต่างๆ ได้แก่ - Bootstrap, Extensions และ System class loaders Bootstrap ทำหน้าที่เป็นพาเรนต์สำหรับพวกเขาทั้งหมดและรับผิดชอบในการโหลดคลาสภายใน JDK ในทางกลับกันส่วนขยายและระบบโหลดคลาสจากไดเร็กทอรีส่วนขยาย Java และ classpath ตามลำดับ

จากนั้นเราได้พูดคุยเกี่ยวกับวิธีการทำงานของรถตักชั้นเรียนและเราได้พูดถึงคุณลักษณะบางอย่างเช่นการมอบหมายการมองเห็นและความเป็นเอกลักษณ์ตามด้วยคำอธิบายสั้น ๆ เกี่ยวกับวิธีการสร้างแบบกำหนดเอง ในที่สุดเราได้ให้ข้อมูลเบื้องต้นเกี่ยวกับรถตักระดับบริบท

ตัวอย่างโค้ดเช่นเคยสามารถพบได้ใน GitHub