關于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();
相關文章:
1. javascript - js setTimeout在雙重for循環中如何使用?2. atom開始輸入!然后按tab只有空格出現沒有html格式出現3. java - 線上應用,如果數據庫操作失敗的話應該如何處理?4. MySQL中的enum類型有什么優點?5. MYSQL 根據兩個字段值查詢 但兩個值的位置可能是互換的,這個怎么查?6. css - 如何選擇字體?7. javascript - 有適合開發手機端Html5網頁小游戲的前端框架嗎?8. javascript - h5微信中怎么禁止橫屏9. mysql - linux連接數據庫報錯10. mysql - 這種分級一對多,且分級不平衡的模型該怎么設計表?
