關(guān)于JAVA類加載器。
問(wèn)題描述
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 {//測(cè)試1Object obj2 = classLoader('com.myweb.reflect.classloader.ClassLoaderTest');System.out.println(obj2.getClass());System.out.println(obj2 instanceof com.myweb.reflect.classloader.ClassLoaderTest);//測(cè)試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
為什么兩段相同的代碼,只是一個(gè)單獨(dú)提取出來(lái),輸出就不一樣了呢?
問(wèn)題解答
回答1:你確定是兩段相同的代碼嗎?第一個(gè)代碼段里面有多一句return (T) myClassLoader.loadClass(className).newInstance();
相關(guān)文章:
1. boot2docker無(wú)法啟動(dòng)2. docker-compose中volumes的問(wèn)題3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. java - SSH框架中寫分頁(yè)時(shí)service層中不能注入分頁(yè)類5. nignx - docker內(nèi)nginx 80端口被占用6. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.7. javascript - mock.js可以存儲(chǔ)數(shù)據(jù)嗎8. docker api 開發(fā)的端口怎么獲取?9. docker images顯示的鏡像過(guò)多,狗眼被亮瞎了,怎么辦?10. golang - 用IDE看docker源碼時(shí)的小問(wèn)題

網(wǎng)公網(wǎng)安備