A classic example of the loading sequence of the class loader and a classic example of the loading sequence
Q: What happens if I define a java. lang. String and run it?
Let's look at the following code:
1 package java.lang;2 public class String{3 public static void main(String[] args ){ 4 }5 }
What are the differences? By the way, we have written a class that is exactly the same as the String in JDK, and even the java. lang package is the same. The only difference is that our custom String class has a main function. Let's run it:
Java. lang. NoSuchMethodError: main
Exception in thread "main"
Why? Isn't there a main method in our String class?
In fact, when we contact the parent-parent Delegation Model loaded by the jvm class, we can explain this problem.
Run this code. AppClassLoader will try to load java. lang. string class, but according to the parent-parent delegate model AppClassLoader will load java. lang. the String request is delegated to ExtClassLoader, and ExtClassLoader is delegated to the final start class loader BootstrapLoader.
The BootstrapLoader can only load the class (J2SE API) in JAVA_HOME \ jre \ lib. The problem is that there is indeed a java in the standard API. lang. string (note that this class and our custom class are completely two classes ). BootstrapLoader thought that he had found this class and did not hesitate to load java. lang. String in j2se api.
Finally, the above loading error occurs (note that it is not an exception, it is an error, and JVM exits), because the String class in the API does not have the main method.
Conclusion: Of course we can define a class that is exactly the same as the API, but because of the parent-child delegate model, we cannot load the class we have customized. Therefore, the J2SE specification requires that our custom packages have their own unique characteristics (network domain names ). Another point is that this loader makes the JVM more secure to run programs, because it is difficult for hackers to replace the code in the API at will.
Reference: http://hxraid.iteye.com/blog/747625