2014-07-02 25 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正确,您采取的行动在每种情况下都是相同的,所以您不需要不同的处理程序。 –

相关问题