2013-07-24 103 views
0

我嘗試編寫我自己的加載類的加載類。Java:從超級構造函數捕獲異常

因此,我也覆蓋構造loader(ClassLoader paramClassLoader, File paramFile),其調用super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);

呼叫 「.toUrl()」 可以拋出MalformedURLException,所以編譯如下代碼...

public class loader extends URLClassLoader { 
    public static void main(String[] args)throws Exception{ 
     Object localObject = 
      new loader(loader.class.getClassLoader(), 
          new File(loader.class.getProtectionDomain().getCodeSource() 
           .getLocation().getPath()) 
       ); 
     (...) 
    } 

    private loader(ClassLoader paramClassLoader, File paramFile){ 
     super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader); 

     if (paramClassLoader == null) 
      throw new IllegalArgumentException("Error loading class"); 
    } 
} 

錯誤:

loader.java:123: error: unreported exception MalformedURLException; must be caught or declared to be thrown 
super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader); 

我怎麼能捕獲此異常? try-catch-block是不可能的,因爲「super super call必須是構造函數中的第一條語句」。

+1

一般來說,你應該避免在構造函數中發生任何類型的異常。爲什麼不傳遞paramFile.toURI()。toURL()作爲構造函數的參數?通過這種方式,您可以在創建對象之前捕獲異常。 –

回答

3

只需將MalformedURLException添加到加載器構造函數中,並使用try catch塊在main方法中包裝代碼。

public class loader extends URLClassLoader { 

    public static void main(String[] args) throws Exception { 
     try { 
      Object localObject = new loader(loader.class.getClassLoader(), 
        new File(loader.class.getProtectionDomain().getCodeSource() 
          .getLocation().getPath())); 
     } catch (MalformedURLException e) { 
      // .. 
     } 
    } 

    private loader(ClassLoader paramClassLoader, File paramFile) 
      throws MalformedURLException { 
     super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader); 

     if (paramClassLoader == null) { 
      throw new IllegalArgumentException("Error loading class"); 
     } 
    } 
} 
+0

謝謝,這工作。我嘗試了類似的(沒有)工作,所以我沒有看到只是添加(try-catch和throws)。問題解決了。 – CFP

7

這個異常實際上並沒有被超類的構造函數拋出;它被拋出(或者至少聲明可能被拋出)URI.toURL(),你在調用你的參數給超類的構造函數。

一種選擇是寫一個靜態方法來該異常轉換爲未選中一個:

private static URL convertFileToURL(File file) { 
    try { 
     return file.toURI().toURL(); 
    } catch (MalformedURLException e) { 
     throw new RuntimeException("Unable to convert file to URL", e); 
    } 
} 

然後:

private loader(ClassLoader paramClassLoader, File paramFile){ 
    super(new URL[] { convertFileToURL(paramFile) }, paramClassLoader); 

    if (paramClassLoader == null) 
     throw new IllegalArgumentException("Error loading class"); 
} 

這是假設你認爲這是什麼,基本上不能發生,或至少是你不希望呼叫者關心的。我不知道URI.toURL是否是實際上是對基於文件的URI的關注。如果來電者應該小心,因爲它可能發生在現實生活中,他們應該處理它(我認爲這不太可能是誠實的),你應該聲明你的構造函數可以拋出異常。

順便說一下,請將您的類重命名爲更符合Java命名約定的內容。

+0

感謝您的解釋。 – CFP

+0

@PKKG:請不要將對完全無關的帖子的引用添加爲註釋。 –