The JVM uses an on-demand loading method for bytecode files. When does this Class load its bytecode into memory to generate a Class object? Let’s test the parental delegation mechanism with a case study.
package java.lang; Public class String {static{system.out.println (" custom String"); }} package com.bjsxt.test01; public class Test { public static void main(String[] args) { java.lang.String str = new java.lang.String(); }}Copy the code
Does this String load a JDK supplied String or my own String? The answer is to load a String provided by the JDK, using the parent delegate mechanism.
1. What is parental delegation
Working principle:
1) If a classloader receives a classload request, it does not load the request itself. Instead, it delegates the request to the parent class’s loader.
2) If the parent class loader still has its parent class loader, the request will reach the starting class loader of the item layer by further delegating and recursively;
3) If the parent class loader can complete the task, it returns successfully. If the parent class loader cannot complete the task, the child loader will try to load itself. This is the parent delegate mechanism.
If the String class is defined by itself, then the loader of the custom class is the system class loader, so delegate up, all the way to the top of the boot class loader, and the boot class loader can load the String in the core library. The extension class loader is responsible for this, so it loads the String in the JDK.
So if you want to load a custom Student, you delegate it layer by layer, but nobody else does, so you have to use the system loader!
2. Why parent delegation
Because if I randomly execute my own String, then you say your perfect project, if I maliciously attack you to send you a String class, then your project will not directly crash? This is also a kind of protection!
1) Avoid core API tampering
2) Avoid class reloading
Consider why this code fails:
public class String { public static void main(String[] args) { System.out.println("xixi"); }}
Copy the code
Because of what? The extension class loader found a String in the core library, but there is no main method in the core class, so there is an error.
So don’t define the same package (java.lang.Student) as the core API, the same class (java.lang.string) will return an error.
The following is a small series through some large factory friends to their internal Java interview questions, information is rare, but also nearly a year of real interview questions;
There are: Ant Financial, Pinduoduo, Ali Cloud, Baidu, Vipshop, Ctrip and other primary, intermediate, advanced Java interview questions set, with super detailed answers, I hope to help you.