2014-07-02 24 views
0

我的程序被設計爲從一個可運行的jar文件啓動,如果需要的話將所有東西都設置好,然後在另一個jar文件中加載一個類來啓動程序。這允許自我更新,重新啓動等。嗯,類加載代碼我似乎有點時髦。以下是我用來加載程序的代碼。這是不正確的使用還是不好的做法?這是不正確的使用還是類加載器的不良做法?

try { 
     Preferences.userRoot().put("clientPath", Run.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()); //Original client location; helps with restarts 
    } catch (URISyntaxException e1) { 
     e1.printStackTrace(); 
    } 

    try { 
     Preferences.userRoot().flush(); 
    } catch (BackingStoreException e1) { 
     e1.printStackTrace(); 
    } 


    File file = new File(path); // path of the jar we will be launching to initiate the program outside of the Run class 
    URL url = null; 
    try { 
     url = file.toURI().toURL(); // converts the file path to a url 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } 
    URL[] urls = new URL[] { url }; 
    ClassLoader cl = new URLClassLoader(urls); 

    Class cls = null; 
    try { 
     cls = cl.loadClass("com.hexbit.EditorJ.Load"); // the class we are loading to initiate the program 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 

    try { 
     cls.newInstance(); // starts the class that has been loaded and the program is on its way 
    } catch (InstantiationException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } 

回答

1

你有最大的問題是,當你得到你假裝記錄異常使得OK繼續,彷彿什麼都沒有發生異常。

如果您將try/catch塊聚合在一起,那麼您的代碼將會更短且更易於閱讀,並且不會認爲異常並不重要。

試試這個例子

public static Object load(String path, String className) { 
    try { 
     URL url = new File(path).toURI().toURL(); 
     ClassLoader cl = new URLClassLoader(new URL[] { url }); 
     return cl.loadClass(className).newInstance(); 
    } catch (Exception e) { 
     throw new IllegalStateException("Unable to load "+className+" " + e); 
    } 
} 
+0

把它在一個try塊一樣,似乎有點普通,但你可以從例外五異常的類型,是否正確? – Frizinator

+0

@StevenTylerFrizell正確,您採取的行動在每種情況下都是相同的,所以您不需要不同的處理程序。 –

相關問題