【问题标题】:Is this incorrect use or bad practice of class loaders?这是类加载器的错误使用还是不良做法?
【发布时间】:2014-07-02 17:58:12
【问题描述】:

我的程序设计为从一个可运行的 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();
    }

【问题讨论】:

    标签: java class classloader


    【解决方案1】:

    您遇到的最大问题是,当您收到异常时,您假装记录异常可以继续,就好像什么都没发生一样。

    如果您聚合 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);
        }
    }
    

    【讨论】:

    • 像这样放在 try 块中似乎有点笼统,但是您可以从 Exception e 中获取异常的类型,对吗?
    • @StevenTylerFrizell 正确,您在每种情况下采取的操作都是相同的,因此您不需要为它们使用不同的处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多