關于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. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?2. docker start -a dockername 老是卡住,什么情況?3. docker容器呢SSH為什么連不通呢?4. Android listview checkbox 單選5. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””6. Android TextView 或 ListView 加載過渡效果7. python-mysql Commands out of sync8. Python列表或者字典里面的中文如何處理?9. 爬蟲圖片 - 關于Python 爬蟲的問題10. python - (初學者)代碼運行不起來,求指導,謝謝!
