[問題] URLClassLoader 釋放 .jar檔 已解決

看板java作者 (SSLin)時間6年前 (2018/03/26 10:51), 6年前編輯推噓0(002)
留言2則, 2人參與, 6年前最新討論串1/1
環境 win7 版本: jdk1.2 寫了一段 function 載入 .jar 檔執行 然後希望 function 結束後刪除 .jar 檔 但是不知道為何 .jar檔無法被刪除 code 大致如下 URL url = new URL("file:/C:/java/A.jar"); URLClassLoader ul = new URLClassLoader(new URL[] { url }); Class c = ul.loadClass(name); Method m = c.getMethod("main", new Class[] { args.getClass() }); m.setAccessible(true); int mods = m.getModifiers(); if ( !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) { throw new NoSuchMethodException("main"); } try { String result = m.invoke(null, new Object[] { args }).toString(); if(result.indexOf("0")!=-1) System.out.println("Close"); File f=new File("C:/java/A.jar"); if(f.exists()){ System.out.println("Delete Old jar"); f.delete(); } } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } delete 部分也沒跳 exception, 但是 A.jar還在 沒有被刪除 手動刪除的話 windows 會跳出訊息說正被 java 使用 無法被刪除 google 之後找不太到解法 有看到說可以呼叫 URLClassLoader.close() 但是 java 1.2 沒有 不知道如何解決 請問版上的各位大大有好的辦法嗎? ------------------------ 如果換 java 1.8 呼叫 URLClassLoader.close() 可以正常刪除 1.2 有相應的功能嗎? ------------ 我眼殘 不知道之前為什麼一直都沒找到這篇 https://stackoverflow.com/a/31114719 參考 stackoverflow 的解法 透過 reflect 強行關閉 jar file 已可正常刪除檔案 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.37.141.97 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1522032715.A.982.html ※ 編輯: libertyleave (114.37.141.97), 03/26/2018 11:06:59 ※ 編輯: libertyleave (114.37.141.97), 03/26/2018 12:52:17

03/27 09:00, 6年前 , 1F
一定要1.2這麼悲劇?
03/27 09:00, 1F

03/27 09:56, 6年前 , 2F
就是這麼悲劇
03/27 09:56, 2F
文章代碼(AID): #1Qk61Bc2 (java)