Class Loader, class loading
In my heart, class loading has always been fascinating, mainly because I think how this process works. I have recently summarized what I have learned before, so I will summarize the class loaders.
I think the main reason for putting such an important thing as loading classes outside the JVM is to provide better scalability, let programmers decide how to load a class on their own. According to the book, this class loader was originally designed to satisfy the JAVA Applet, but I am newbie and have never experienced that period, it can only be blinded by the old birds for one year. However, nowadays, the main direction of class loading is class hierarchy,OSGi,Hot deployment, code encryption and other fields have been well utilized.
1. Classes and class loaders
Although the loader is only used to load the class action, it does not, because each class loader has its own class namespace, that is, the two classes only make sense when they come from the same class loader. Otherwise, even if they come from the same bytecode, they will not be the same, even if they are judged using the instanceof keyword.
Package com. hotusm. classloader; import java. io. inputStream; import org. junit. test;/***** @ author Hotusm <br/> * @ date August 1, October 29, 2016 <br/> * @ description */public class ClassLoaderTest {@ Test public void test () throws ClassNotFoundException {PathClassLoader classLoader = new PathClassLoader ("D:/jeesite/ActOfJava/bin"); Class <?> LoadClass = classLoader. findClass ("com. hotusm. classloader. classLoaderTest "); System. out. println (loadClass) ;}@ Test public void testClassPath () {ClassLoader classLoader = new ClassLoader () {@ Override public Class <?> LoadClass (String name) throws ClassNotFoundException {if (! Name. startsWith ("com. hotusm ") return super. loadClass (name); String fileName = name. substring (name. lastIndexOf (". ") + 1) + ". class "; try (InputStream is = getClass (). getResourceAsStream (fileName) {if (is = null) {super. loadClass (name);} byte [] B = new byte [is. available ()]; is. read (B); return defineClass (name, B, 0, B. length);} catch (Exception e) {e. printStackTrace () ;}return null ;}; try {Object obj = classLoader. loadClass ("com. hotusm. classloader. classLoaderTest "). newInstance (); // Method method = obj. getClass (). getMethod ("testMethod"); // method. invoke (obj); System. out. println (obj instanceof com. hotusm. classloader. classLoaderTest);} catch (Exception e) {e. printStackTrace () ;}} public void testMethod () {System. out. println ("method ");}}
The output above is false !! (The annotation is also a code encryption idea. It encrypts the bytecode file and then customizes the class loader to implement decryption and decrypt the bytecode, last reflection call)
2. Parental Delegation Model:
The parent-child assignment is to delegate the duties up to the top level. If the top layer cannot be parsed, delegate next until the resolution is successful,
3. class loaders:
Bootstrap class loader ):
It is used to load the Java core library (jre/lib/rt. jar). It is implemented using native C ++ code and does not inherit from java. lang. ClassLoader.
Load the extension class and application class loaders and specify their parent class loaders, which cannot be obtained in java.
Extensions class loader ):
It is used to load Java extension libraries (jre/ext/*. jar ). The Java virtual machine provides an extension library directory. This class loader searches for and loads Java classes in this directory.
System class loader ):
It loads the Java class according to the CLASSPATH of the Java application. Generally, Java application classes are loaded by them. You can obtain it through ClassLoader. getSystemClassLoader.
Custom class loader ):
In addition to the class loaders provided by the system, developers can inherit the java. lang. ClassLoader class to implement their own class loaders to meet some special requirements.
The following is a self-defined Class Loader:
Package com. hotusm. classloader; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. util. map; import java. util. concurrent. concurrentHashMap; /***** @ author Hotusm <br/> * @ date October 28, 2016 <br/> * @ description Class Loader * http://www.cnblogs.com/sunniest/p/4574080.html ** tree hierarchy of class loaders in JVM * Guide bootstrap class loader) * extended Class Loader (ex Tensions class loader) * system class loader * custom class loader **/public class PathClassLoader extends ClassLoader {private String classPath; private String packageNames = "com. hotusm "; private Map <String, Class <?> Cache = new ConcurrentHashMap <> (); public PathClassLoader (String classPath) {this. classPath = classPath ;}@ Override protected Class <?> FindClass (String name) throws ClassNotFoundException {if (name. startsWith (packageNames) {return cacheClass (name);} else {return super. findClass (name) ;}} private byte [] getData (String className) {String path = classPath + File. separatorChar + className. replace ('. ', File. separatorChar) + ". class "; try (InputStream is = new FileInputStream (path) {ByteArrayOutputStream stream = new ByteArrayOutputStream (); B Yte [] buffer = new byte [2014]; int num = 0; while (num = is. read (buffer ))! =-1) {stream. write (buffer, 0, num);} return stream. toByteArray ();} catch (Exception e) {e. printStackTrace ();} return null;} private Class <?> CacheClass (final String name) throws ClassNotFoundException {Class <?> Clazz = cache. get (name); synchronized (name) {if (clazz = null) {byte [] classData = getData (name); if (classData = null) {throw new ClassNotFoundException ();} else {clazz = defineClass (name, classData, 0, classData. length); cache. put (name, clazz) ;}} return clazz ;}}