Load jar dynamically at runtime?

前端 未结 2 472
闹比i
闹比i 2021-01-05 08:59

My current java project is using methods and variables from another project (same package). Right now the other project\'s jar has to be in the classpath to work correctly.

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 09:30

    I needed to load a jar file at runtime for both java 8 and java 9+. Here is the method to do it (using Spring Boot 1.5.2 if it may relate).

    public static synchronized void loadLibrary(java.io.File jar) {
        try {            
            java.net.URL url = jar.toURI().toURL();
            java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
            method.setAccessible(true); /*promote the method to public access*/
            method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
        } catch (Exception ex) {
            throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
        }
    }
    

提交回复
热议问题