Can I dynamically unload and reload (other versions of the same) JAR?

前端 未结 6 780
北恋
北恋 2020-12-05 07:40

I am writing a server program which is used to run unit tests of an API (displaying lots of information and providing web access to control / monitor the whole thing)...<

6条回答
  •  -上瘾入骨i
    2020-12-05 08:24

    You could programatically modify your classpath to reflect your JAR changes. Here is how I would do it:

      URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
            m.setAccessible(true);
            m.invoke(urlClassLoader, jarFile.toURI().toURL());
            String cp = System.getProperty("java.class.path");
            if (cp != null) {
                cp += File.pathSeparatorChar + jarFile.getCanonicalPath();
            } else {
                cp = jarFile.toURI().getPath();
            }
            System.setProperty("java.class.path", cp);
    

    where jarFile is the version of the jar you want to use/overwrite.

提交回复
热议问题