關于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. Python從URL中提取域名2. php傳對應的id值為什么傳不了啊有木有大神會的看我下方截圖3. python - scrapy url去重4. python - Flask寫的注冊頁面,當注冊時,如果填寫數(shù)據(jù)庫里有的相同數(shù)據(jù),就報錯5. 關于mysql聯(lián)合查詢一對多的顯示結果問題6. 實現(xiàn)bing搜索工具urlAPI提交7. 數(shù)據(jù)庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。8. python - oslo_config9. MySQL主鍵沖突時的更新操作和替換操作在功能上有什么差別(如圖)10. 小白學python的問題 關于%d和%s的區(qū)別
