關(guān)于JAVA類加載器。
問題描述
public static <T> T classLoader(String className) throws Exception {ClassLoader myClassLoader = new ClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException {try { //獲取類文件名 String fileName = name.substring(name.lastIndexOf('.') + 1) + '.class'; InputStream inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) {return super.findClass(fileName); } byte[] bytes = new byte[inputStream.available()]; inputStream.close(); return defineClass(name, bytes, 0, bytes.length);} catch (IOException e) { throw new ClassNotFoundException();} }};return (T) myClassLoader.loadClass(className).newInstance(); }public static void main(String[] args) throws Exception {//測試1Object obj2 = classLoader('com.myweb.reflect.classloader.ClassLoaderTest');System.out.println(obj2.getClass());System.out.println(obj2 instanceof com.myweb.reflect.classloader.ClassLoaderTest);//測試2ClassLoader myClassLoader = new ClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException {try { //獲取類文件名 String fileName = name.substring(name.lastIndexOf('.') + 1) + '.class'; InputStream inputStream = getClass().getResourceAsStream(fileName); if (inputStream == null) {return super.findClass(fileName); } byte[] bytes = new byte[inputStream.available()]; inputStream.close(); return defineClass(name, bytes, 0, bytes.length);} catch (IOException e) { throw new ClassNotFoundException();} }};Object obj3 = myClassLoader.loadClass('com.myweb.reflect.classloader.ClassLoaderTest');System.out.println(obj3.getClass());System.out.println(obj3 instanceof com.myweb.reflect.classloader.ClassLoaderTest);}
輸出:class com.myweb.reflect.classloader.ClassLoaderTesttrueclass java.lang.Classfalse
為什么兩段相同的代碼,只是一個單獨提取出來,輸出就不一樣了呢?
問題解答
回答1:你確定是兩段相同的代碼嗎?第一個代碼段里面有多一句return (T) myClassLoader.loadClass(className).newInstance();
相關(guān)文章:
1. mysql優(yōu)化 - 關(guān)于mysql分區(qū)2. javascript - 循環(huán)嵌套多個promise應(yīng)該如何實現(xiàn)?3. 前端 - IE9 css兼容問題4. css - 移動端字體設(shè)置問題5. html5 - 如何實現(xiàn)帶陰影的不規(guī)則容器?6. vue.js - vue 打包后 nginx 服務(wù)端API請求跨域問題無法解決。7. javascript - ionic2 input autofocus 電腦成功,iOS手機鍵盤不彈出8. node.js - 在vuejs-templates/webpack中dev-server.js里為什么要exports readyPromise?9. css3 - rem布局下,用戶瀏覽器的最小字號是12px怎么辦?10. objective-c - iOS開發(fā)支付寶和微信支付完成為什么跳轉(zhuǎn)到了之前開發(fā)的一個app?
