JVM(五),ClassLoader
阿新 • • 發佈:2019-02-12
output ava get length 文件 ray trace 調用 aid
五、ClassLoader
1.什麽是ClassLoader
2.四種ClassLoader
3.自定義CLassLoader
(1)MyClassLoader
public class MyClassLoader extends ClassLoader { private String path; private String classLoaderName; public MyClassLoader(String path, String classLoaderName) { this.path = path; this.classLoaderName = classLoaderName; } //用於尋找類文件 @Override public Class findClass(String name) { byte[] b = loadClassData(name); return defineClass(name, b, 0, b.length); } //用於加載類文件 private byte[] loadClassData(String name) { name = path + name + ".class"; InputStream in= null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File(name)); out = new ByteArrayOutputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } } catch (Exception e) { e.printStackTrace(); }finally { try { out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } return out.toByteArray(); } }
原理還是通過ClassLoader中的deFineClass方法來獲取Class類型對象,自定義的是路徑
(2)實現ClassLoaderChecker
public class ClassLoaderChecker { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { MyClassLoader m = new MyClassLoader("/Users/baidu/Desktop/", "myClassLoader"); Class c = m.loadClass("Wali"); c.newInstance(); } }
(3)實現效果
4.類加載器的雙親委派機制
為什麽要使用雙親委派機制來加載class文件-避免多份同樣的字節碼的加載
5.類的加載方式
隱式加載:new
顯示加載:loadClass,formName
(1)類裝載過程
(2)代碼實例區別
public class LoadDifference { public static void main(String[] args) throws Exception { //loadClass加載類,需要調用c.newInstance()才會加載類 ClassLoader cl = Robot.class.getClassLoader(); Class c = cl.loadClass("com.interview.javabasic.reflect.Robot"); c.newInstance(); //forName加載類,在加載類的時候會將Static靜態代碼塊的代碼實現出來 Class r = Class.forName("com.interview.javabasic.reflect.Robot"); } }
使用Class.forName(classname)才能在反射回去類的時候執行static塊。(3)數據庫鏈接為什麽使用Class.forName(className)
JVM(五),ClassLoader