java基本進修筆記之類加載器。本站提示廣大學習愛好者:(java基本進修筆記之類加載器)文章只能為提供參考,不一定能成為您想要的結果。以下是java基本進修筆記之類加載器正文
類加載器
java類加載器就是在運轉時在JVM中靜態地加載所需的類,java類加載器基於三個機制:拜托,可見,單一。
把classpath下的那些.class文件加載進內存,處置後成為字節碼,這些任務是類加載器做的。
默許類加載器
體系默許三個類加載器:
類加載器也是java類,而BootStrap不是。 驗證代碼:
public class ClassLoaderTest { public static void main(String[] args) { System.out.println(System.class.getClassLoader()); } }
輸入:null
假如應用System.out.println(System.class.getClassLoader().toString);,則報空指針異常:
Exception in thread "main" java.lang.NullPointerException at com.iot.classloader.ClassLoaderTest.main(ClassLoaderTest.java:10) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
可見,System類是由BootStrap類加載器加載。
類加載器的拜托機制
類加載器的樹狀圖
類加載器
普通加載類的次序:
自界說類加載器的編寫道理
API:
Class ClassLoader
模板辦法設計形式
父類:
loadClass(類加載的流程,模板)
findClass供子類籠罩的、被loadClass辦法挪用的類加載邏輯
defineClass獲得class文件轉換成字節碼
子類:籠罩findClass辦法
例子:
loadClass辦法的源碼
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. long t1 = System.nanoTime(); c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } }
API文檔中的例子:
class NetworkClassLoader extends ClassLoader { String host; int port; public Class findClass(String name) { byte[] b = loadClassData(name); return defineClass(name, b, 0, b.length); } private byte[] loadClassData(String name) { // load the class data from the connection . . . } }