<p>Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own <code>ClassLoader</code>, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.</p>

<p>Any suggestions for simple code that does this?</p>

[{'answer_id': 60766, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 7, 'selected': False, 'text': '<p>The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:</p>\n\n<pre><code>File file = ...\nURL url = file.toURI().toURL();\n\nURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\nMethod method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);\nmethod.setAccessible(true);\nmethod.invoke(classLoader, url);\n</code></pre>\n'}, {'answer_id': 60770, 'author': 'Martin Klinke', 'author_id': 1793, 'author_profile': 'https://Stackoverflow.com/users/1793', 'pm_score': 6, 'selected': False, 'text': '<p>You should take a look at <a href="http://www.osgi.org" rel="noreferrer">OSGi</a>, e.g. implemented in the <a href="http://www.eclipse.org" rel="noreferrer">Eclipse Platform</a>. It does exactly that. You can install, uninstall, start and stop so called bundles, which are effectively JAR files. But it does a little more, as it offers e.g. services that can be dynamically discovered in JAR files at runtime.</p>\n\n<p>Or see the specification for the <a href="http://jcp.org/en/jsr/detail?id=277" rel="noreferrer">Java Module System</a>.</p>\n'}, {'answer_id': 60775, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 9, 'selected': True, 'text': '<p>The reason it\'s hard is security.  Classloaders are meant to be immutable; you shouldn\'t be able to willy-nilly add classes to it at runtime.  I\'m actually very surprised that works with the system classloader.  Here\'s how you do it making your own child classloader:</p>\n\n<pre><code>URLClassLoader child = new URLClassLoader(\n        new URL[] {myJar.toURI().toURL()},\n        this.getClass().getClassLoader()\n);\nClass classToLoad = Class.forName("com.MyClass", true, child);\nMethod method = classToLoad.getDeclaredMethod("myMethod");\nObject instance = classToLoad.newInstance();\nObject result = method.invoke(instance);\n</code></pre>\n\n<p>Painful, but there it is.</p>\n'}, {'answer_id': 63892, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>The best I\'ve found is <a href="http://svn.apache.org/viewvc/geronimo/xbean/trunk/xbean-classloader/src/main/java/org/apache/xbean/classloader/JarFileClassLoader.java?view=markup" rel="noreferrer">org.apache.xbean.classloader.JarFileClassLoader</a> which is part of the <a href="http://geronimo.apache.org/xbean" rel="noreferrer">XBean</a> project.</p>\n\n<p>Here\'s a short method I\'ve used in the past, to create a class loader from all the lib files in a specific directory</p>\n\n<pre><code>public void initialize(String libDir) throws Exception {\n    File dependencyDirectory = new File(libDir);\n    File[] files = dependencyDirectory.listFiles();\n    ArrayList&lt;URL&gt; urls = new ArrayList&lt;URL&gt;();\n    for (int i = 0; i &lt; files.length; i++) {\n        if (files[i].getName().endsWith(".jar")) {\n        urls.add(files[i].toURL());\n        //urls.add(files[i].toURI().toURL());\n        }\n    }\n    classLoader = new JarFileClassLoader("Scheduler CL" + System.currentTimeMillis(), \n        urls.toArray(new URL[urls.size()]), \n        GFClassLoader.class.getClassLoader());\n}\n</code></pre>\n\n<p>Then to use the classloader, just do: </p>\n\n<pre><code>classLoader.loadClass(name);\n</code></pre>\n'}, {'answer_id': 1450837, 'author': 'Chris', 'author_id': 92813, 'author_profile': 'https://Stackoverflow.com/users/92813', 'pm_score': 5, 'selected': False, 'text': '<p>How about the <a href="https://github.com/kamranzafar/JCL" rel="noreferrer">JCL class loader framework</a>? I have to admit, I haven\'t used it, but it looks promising.</p>\n\n<p>Usage example:</p>\n\n<pre><code>JarClassLoader jcl = new JarClassLoader();\njcl.add("myjar.jar"); // Load jar file  \njcl.add(new URL("http://myserver.com/myjar.jar")); // Load jar from a URL\njcl.add(new FileInputStream("myotherjar.jar")); // Load jar file from stream\njcl.add("myclassfolder/"); // Load class folder  \njcl.add("myjarlib/"); // Recursively load all jar files in the folder/sub-folder(s)\n\nJclObjectFactory factory = JclObjectFactory.getInstance();\n// Create object of loaded class  \nObject obj = factory.create(jcl, "mypackage.MyClass");\n</code></pre>\n'}, {'answer_id': 2593771, 'author': 'Jonathan Nadeau', 'author_id': 311140, 'author_profile': 'https://Stackoverflow.com/users/311140', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a version that is not deprecated. I modified the original to remove the deprecated functionality.</p>\n\n<pre><code>/**************************************************************************************************\n * Copyright (c) 2004, Federal University of So Carlos                                           *\n *                                                                                                *\n * All rights reserved.                                                                           *\n *                                                                                                *\n * Redistribution and use in source and binary forms, with or without modification, are permitted *\n * provided that the following conditions are met:                                                *\n *                                                                                                *\n *     * Redistributions of source code must retain the above copyright notice, this list of      *\n *       conditions and the following disclaimer.                                                 *\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of   *\n *     * conditions and the following disclaimer in the documentation and/or other materials      *\n *     * provided with the distribution.                                                          *\n *     * Neither the name of the Federal University of So Carlos nor the names of its            *\n *     * contributors may be used to endorse or promote products derived from this software       *\n *     * without specific prior written permission.                                               *\n *                                                                                                *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS                            *\n * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT                              *\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR                          *\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR                  *\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,                          *\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,                            *\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR                             *\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF                         *\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING                           *\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS                             *\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                                   *\n **************************************************************************************************/\n/*\n * Created on Oct 6, 2004\n */\npackage tools;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.net.URLClassLoader;\n\n/**\n * Useful class for dynamically changing the classpath, adding classes during runtime. \n */\npublic class ClasspathHacker {\n    /**\n     * Parameters of the method to add an URL to the System classes. \n     */\n    private static final Class&lt;?&gt;[] parameters = new Class[]{URL.class};\n\n    /**\n     * Adds a file to the classpath.\n     * @param s a String pointing to the file\n     * @throws IOException\n     */\n    public static void addFile(String s) throws IOException {\n        File f = new File(s);\n        addFile(f);\n    }\n\n    /**\n     * Adds a file to the classpath\n     * @param f the file to be added\n     * @throws IOException\n     */\n    public static void addFile(File f) throws IOException {\n        addURL(f.toURI().toURL());\n    }\n\n    /**\n     * Adds the content pointed by the URL to the classpath.\n     * @param u the URL pointing to the content to be added\n     * @throws IOException\n     */\n    public static void addURL(URL u) throws IOException {\n        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n        Class&lt;?&gt; sysclass = URLClassLoader.class;\n        try {\n            Method method = sysclass.getDeclaredMethod("addURL",parameters);\n            method.setAccessible(true);\n            method.invoke(sysloader,new Object[]{ u }); \n        } catch (Throwable t) {\n            t.printStackTrace();\n            throw new IOException("Error, could not add URL to system classloader");\n        }        \n    }\n\n    public static void main(String args[]) throws IOException, SecurityException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{\n        addFile("C:\\\\dynamicloading.jar");\n        Constructor&lt;?&gt; cs = ClassLoader.getSystemClassLoader().loadClass("test.DymamicLoadingTest").getConstructor(String.class);\n        DymamicLoadingTest instance = (DymamicLoadingTest)cs.newInstance();\n        instance.test();\n    }\n}\n</code></pre>\n'}, {'answer_id': 7523747, 'author': 'tanyehzheng', 'author_id': 284126, 'author_profile': 'https://Stackoverflow.com/users/284126', 'pm_score': -1, 'selected': False, 'text': '<p>I personally find that <a href="http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html" rel="nofollow">java.util.ServiceLoader</a> does the job pretty well. You can get an example <a href="http://java.sun.com/developer/technicalArticles/javase/extensible/" rel="nofollow">here</a>.</p>\n'}, {'answer_id': 18253109, 'author': 'Caner', 'author_id': 448625, 'author_profile': 'https://Stackoverflow.com/users/448625', 'pm_score': 3, 'selected': False, 'text': '<p>If you are working on Android, the following code works:</p>\n\n<pre><code>String jarFile = "path/to/jarfile.jar";\nDexClassLoader classLoader = new DexClassLoader(jarFile, "/data/data/" + context.getPackageName() + "/", null, getClass().getClassLoader());\nClass&lt;?&gt; myClass = classLoader.loadClass("MyClass");\n</code></pre>\n'}, {'answer_id': 31624177, 'author': 'venergiac', 'author_id': 1645339, 'author_profile': 'https://Stackoverflow.com/users/1645339', 'pm_score': 2, 'selected': False, 'text': '<p>The solution proposed by jodonnell is good but should be a little bit enhanced. I used this post to develop my application with success. </p>\n\n<h2>Assign the current thread</h2>\n\n<p>Firstly we have to add</p>\n\n<pre><code>Thread.currentThread().setContextClassLoader(classLoader);\n</code></pre>\n\n<p>or you will not able to load resource (such as spring/context.xml) stored into the jar.</p>\n\n<h2>Do not include</h2>\n\n<p>your jars into the parent class loader or you will not able to understand who is loading what.</p>\n\n<p>see also <a href="https://stackoverflow.com/questions/3216780/problem-reloading-a-jar-using-urlclassloader/31624123#31624123">Problem reloading a jar using URLClassLoader</a></p>\n\n<p>However, OSGi framework remain the best way.</p>\n'}, {'answer_id': 46457506, 'author': 'fgb', 'author_id': 298029, 'author_profile': 'https://Stackoverflow.com/users/298029', 'pm_score': 4, 'selected': False, 'text': '<p>With <strong>Java 9</strong>, the answers with <code>URLClassLoader</code> now give an error like:</p>\n\n<pre><code>java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClassLoader\n</code></pre>\n\n<p>This is because the class loaders used have changed. Instead, to add to the system class loader, you can use the <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/instrument/Instrumentation.html" rel="noreferrer">Instrumentation</a> API through an agent.</p>\n\n<p><strong>Create an agent class:</strong></p>\n\n<pre><code>package ClassPathAgent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class ClassPathAgent {\n    public static void agentmain(String args, Instrumentation instrumentation) throws IOException {\n        instrumentation.appendToSystemClassLoaderSearch(new JarFile(args));\n    }\n}\n</code></pre>\n\n<p><strong>Add META-INF/MANIFEST.MF and put it in a JAR file with the agent class:</strong></p>\n\n<pre><code>Manifest-Version: 1.0\nAgent-Class: ClassPathAgent.ClassPathAgent\n</code></pre>\n\n<p><strong>Run the agent:</strong></p>\n\n<p>This uses the <a href="https://github.com/raphw/byte-buddy" rel="noreferrer">byte-buddy-agent</a> library to add the agent to the running JVM:</p>\n\n<pre><code>import java.io.File;\n\nimport net.bytebuddy.agent.ByteBuddyAgent;\n\npublic class ClassPathUtil {\n    private static File AGENT_JAR = new File("/path/to/agent.jar");\n\n    public static void addJarToClassPath(File jarFile) {\n        ByteBuddyAgent.attach(AGENT_JAR, String.valueOf(ProcessHandle.current().pid()), jarFile.getPath());\n    }\n}\n</code></pre>\n'}, {'answer_id': 50521611, 'author': 'Aleksey', 'author_id': 1433446, 'author_profile': 'https://Stackoverflow.com/users/1433446', 'pm_score': 2, 'selected': False, 'text': '<p>please take a look at this project that i started: <a href="https://github.com/avinokurov/proxy-object" rel="nofollow noreferrer">proxy-object lib</a></p>\n\n<p>This lib will load jar from file system or any other location. It will dedicate a class loader for the jar to make sure there are no library conflicts. Users will be able to create any object from the loaded jar and call any method on it. \nThis lib was designed to load jars compiled in Java 8 from the code base that supports Java 7.</p>\n\n<p>To create an object:</p>\n\n<pre><code>    File libDir = new File("path/to/jar");\n\n    ProxyCallerInterface caller = ObjectBuilder.builder()\n            .setClassName("net.proxy.lib.test.LibClass")\n            .setArtifact(DirArtifact.builder()\n                    .withClazz(ObjectBuilderTest.class)\n                    .withVersionInfo(newVersionInfo(libDir))\n                    .build())\n            .build();\n    String version = caller.call("getLibVersion").asString();\n</code></pre>\n\n<p>ObjectBuilder supports factory methods, calling static functions, and call back interface implementations.\ni will be posting more examples on the readme page.</p>\n'}, {'answer_id': 52616924, 'author': 'czdepski', 'author_id': 10448469, 'author_profile': 'https://Stackoverflow.com/users/10448469', 'pm_score': 2, 'selected': False, 'text': '<p>Another version of the hackish solution from Allain, that also works on JDK 11:</p>\n\n<pre><code>File file = ...\nURL url = file.toURI().toURL();\nURLClassLoader sysLoader = new URLClassLoader(new URL[0]);\n\nMethod sysMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});\nsysMethod.setAccessible(true);\nsysMethod.invoke(sysLoader, new Object[]{url});\n</code></pre>\n\n<p>On JDK 11 it gives some deprecation warnings but serves as a temporary solution those who use Allain solution on JDK 11.</p>\n'}, {'answer_id': 52741647, 'author': 'czdepski', 'author_id': 10448469, 'author_profile': 'https://Stackoverflow.com/users/10448469', 'pm_score': 3, 'selected': False, 'text': '<p>Another working solution using Instrumentation that works for me. It has the advantage of modifying the class loader search, avoiding problems on class visibility for dependent classes:</p>\n\n<p><strong>Create an Agent Class</strong></p>\n\n<p>For this example, it has to be on the same jar invoked by the command line:</p>\n\n<pre><code>package agent;\n\nimport java.io.IOException;\nimport java.lang.instrument.Instrumentation;\nimport java.util.jar.JarFile;\n\npublic class Agent {\n   public static Instrumentation instrumentation;\n\n   public static void premain(String args, Instrumentation instrumentation) {\n      Agent.instrumentation = instrumentation;\n   }\n\n   public static void agentmain(String args, Instrumentation instrumentation) {\n      Agent.instrumentation = instrumentation;\n   }\n\n   public static void appendJarFile(JarFile file) throws IOException {\n      if (instrumentation != null) {\n         instrumentation.appendToSystemClassLoaderSearch(file);\n      }\n   }\n}\n</code></pre>\n\n<p><strong>Modify the MANIFEST.MF</strong></p>\n\n<p>Adding the reference to the agent:</p>\n\n<pre><code>Launcher-Agent-Class: agent.Agent\nAgent-Class: agent.Agent\nPremain-Class: agent.Agent\n</code></pre>\n\n<p>I actually use Netbeans, so <a href="https://stackoverflow.com/a/52728977/10448469">this post</a> helps on how to change the manifest.mf</p>\n\n<p><strong>Running</strong></p>\n\n<p>The <code>Launcher-Agent-Class</code> is only supported on JDK 9+ and is responsible for loading the agent without explicitly defining it on the command line:</p>\n\n<pre><code> java -jar &lt;your jar&gt;\n</code></pre>\n\n<p>The way that works on JDK 6+ is defining the <code>-javaagent</code> argument:</p>\n\n<pre><code>java -javaagent:&lt;your jar&gt; -jar &lt;your jar&gt;\n</code></pre>\n\n<p><strong>Adding new Jar at Runtime</strong></p>\n\n<p>You can then add jar as necessary using the following command:</p>\n\n<pre><code>Agent.appendJarFile(new JarFile(&lt;your file&gt;));\n</code></pre>\n\n<p>I did not find any problems using this on documentation.</p>\n'}, {'answer_id': 52911129, 'author': 'steve212', 'author_id': 10534683, 'author_profile': 'https://Stackoverflow.com/users/10534683', 'pm_score': 2, 'selected': False, 'text': '<p>This can be a late response, I can do it as this (a simple example for fastutil-8.2.2.jar) using jhplot.Web class from DataMelt (<a href="http://jwork.org/dmelt" rel="nofollow noreferrer">http://jwork.org/dmelt</a>)</p>\n\n<pre><code>import jhplot.Web;\nWeb.load("http://central.maven.org/maven2/it/unimi/dsi/fastutil/8.2.2/fastutil-8.2.2.jar"); // now you can start using this library\n</code></pre>\n\n<p>According to the documentation, this file will be download inside "lib/user" and then dynamically loaded, so you can start immediately using classes from this jar file in the same program.</p>\n'}, {'answer_id': 53111471, 'author': 'Anton Tananaev', 'author_id': 2548565, 'author_profile': 'https://Stackoverflow.com/users/2548565', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a quick workaround for Allain\'s method to make it compatible with newer versions of Java:</p>\n\n<pre><code>ClassLoader classLoader = ClassLoader.getSystemClassLoader();\ntry {\n    Method method = classLoader.getClass().getDeclaredMethod("addURL", URL.class);\n    method.setAccessible(true);\n    method.invoke(classLoader, new File(jarPath).toURI().toURL());\n} catch (NoSuchMethodException e) {\n    Method method = classLoader.getClass()\n            .getDeclaredMethod("appendToClassPathForInstrumentation", String.class);\n    method.setAccessible(true);\n    method.invoke(classLoader, jarPath);\n}\n</code></pre>\n\n<p>Note that it relies on knowledge of internal implementation of specific JVM, so it\'s not ideal and it\'s not a universal solution. But it\'s a quick and easy workaround if you know that you are going to use standard OpenJDK or Oracle JVM. It might also break at some point in future when new JVM version is released, so you need to keep that in mind.</p>\n'}, {'answer_id': 59743937, 'author': 'Mordechai', 'author_id': 1751640, 'author_profile': 'https://Stackoverflow.com/users/1751640', 'pm_score': 6, 'selected': False, 'text': '<p>While most solutions listed here are either hacks (pre JDK 9) hard to configure (agents) or just don\'t work anymore (post JDK 9) I find it really surprising that nobody mentioned a <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/ClassLoader.html#getSystemClassLoader()" rel="noreferrer">clearly documented method</a>.</p>\n<p>You can create a custom system class loader and then you\'re free to do whatever you wish. No reflection required and all classes share the same classloader.</p>\n<p>When starting the JVM add this flag:</p>\n<pre><code>java -Djava.system.class.loader=com.example.MyCustomClassLoader\n</code></pre>\n<p>The classloader must have a constructor accepting a classloader, which must be set as its parent. The constructor will be called on JVM startup and the real system classloader will be passed, the main class will be loaded by the custom loader.</p>\n<p>To add jars just call <code>ClassLoader.getSystemClassLoader()</code> and cast it to your class.</p>\n<p>Check out <a href="https://github.com/update4j/update4j/blob/master/src/main/java/org/update4j/DynamicClassLoader.java" rel="noreferrer">this implementation</a> for a carefully crafted classloader. Please note, you can change the <code>add()</code> method to public.</p>\n'}, {'answer_id': 60281394, 'author': 'Bằng Rikimaru', 'author_id': 2028440, 'author_profile': 'https://Stackoverflow.com/users/2028440', 'pm_score': 1, 'selected': False, 'text': '<p>I needed to load a jar file at runtime for both java 8 and java 9+ (above comments don\'t work for both of these versions). Here is the method to do it (using Spring Boot 1.5.2 if it may relate).</p>\n\n<pre><code>public static synchronized void loadLibrary(java.io.File jar) {\n    try {            \n        java.net.URL url = jar.toURI().toURL();\n        java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});\n        method.setAccessible(true); /*promote the method to public access*/\n        method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});\n    } catch (Exception ex) {\n        throw new RuntimeException("Cannot load library from jar file \'" + jar.getAbsolutePath() + "\'. Reason: " + ex.getMessage());\n    }\n}\n</code></pre>\n'}, {'answer_id': 60662896, 'author': 'ZGorlock', 'author_id': 7427882, 'author_profile': 'https://Stackoverflow.com/users/7427882', 'pm_score': 2, 'selected': False, 'text': '<p>In case anyone searches for this in the future, this way works for me with OpenJDK 13.0.2.</p>\n\n<p>I have many classes that I need to instantiate dynamically at runtime, each potentially with a different classpath.</p>\n\n<p>In this code, I already have an object called pack, that holds some metadata about the class I am trying to load. The getObjectFile() method returns the location of the class file for the class. The getObjectRootPath() method returns the path to the bin/ directory containing the class files that include the class I am trying to instantiate. The getLibPath() method returns the path to a directory containing the jar files constituting the classpath for the module the class is a part of.</p>\n\n<pre><code>File object = new File(pack.getObjectFile()).getAbsoluteFile();\nObject packObject;\ntry {\n    URLClassLoader classloader;\n\n    List&lt;URL&gt; classpath = new ArrayList&lt;&gt;();\n    classpath.add(new File(pack.getObjectRootPath()).toURI().toURL());\n    for (File jar : FileUtils.listFiles(new File(pack.getLibPath()), new String[] {"jar"}, true)) {\n        classpath.add(jar.toURI().toURL());\n    }\n    classloader = new URLClassLoader(classpath.toArray(new URL[] {}));\n\n    Class&lt;?&gt; clazz = classloader.loadClass(object.getName());\n    packObject = clazz.getDeclaredConstructor().newInstance();\n\n} catch (Exception e) {\n    e.printStackTrace();\n    throw e;\n}\nreturn packObject;\n</code></pre>\n\n<p>I was using the Maven dependency: org.xeustechnologies:jcl-core:2.8 to do this before, but after moving past JDK 1.8, it sometimes froze and never returned being stuck "waiting for references" at Reference::waitForReferencePendingList().</p>\n\n<p>I am also keeping a map of class loaders so that they can be reused if the class I am trying to instantiate is in the same module as a class that I have already instantiated, which I would recommend.</p>\n'}, {'answer_id': 62801788, 'author': 'Richard Kotal', 'author_id': 5934449, 'author_profile': 'https://Stackoverflow.com/users/5934449', 'pm_score': 1, 'selected': False, 'text': '<p>For dynamic uploading of jar files, you can use my modification of URLClassLoader. This modification has no problem with changing the jar file during application operation, like the standard URLClassloader. All loaded jar files are loaded into RAM and thus independent of the original file.</p>\n<p><a href="https://github.com/kotalr/b2b-jcl" rel="nofollow noreferrer">In-memory jar and JDBC class loader</a></p>\n'}, {'answer_id': 63094644, 'author': 'Sergio Santiago', 'author_id': 1563297, 'author_profile': 'https://Stackoverflow.com/users/1563297', 'pm_score': 3, 'selected': False, 'text': '<p>I know I\'m late to the party, but I have been using <a href="https://github.com/pf4j/pf4j" rel="noreferrer">pf4j</a>, which is a plug-in framework, and it works pretty well.</p>\n<p>PF4J is a microframework and the aim is to keep the core simple but extensible.</p>\n<p>An example of plugin usage:</p>\n<p>Define an extension point in your application/plugin using ExtensionPoint interface marker:</p>\n<pre><code>public interface Greeting extends ExtensionPoint {\n\n    String getGreeting();\n\n}\n</code></pre>\n<p>Create an extension using <code>@Extension</code> annotation:</p>\n<pre><code>@Extension\npublic class WelcomeGreeting implements Greeting {\n\n    public String getGreeting() {\n        return &quot;Welcome&quot;;\n    }\n\n}\n</code></pre>\n<p>Then you can load and unload the plugin as you wish:</p>\n<pre><code>public static void main(String[] args) {\n\n    // create the plugin manager\n    PluginManager pluginManager = new JarPluginManager(); // or &quot;new ZipPluginManager() / new DefaultPluginManager()&quot;\n\n    // start and load all plugins of application\n    pluginManager.loadPlugins();\n    pluginManager.startPlugins();\n\n    // retrieve all extensions for &quot;Greeting&quot; extension point\n    List&lt;Greeting&gt; greetings = pluginManager.getExtensions(Greeting.class);\n    for (Greeting greeting : greetings) {\n        System.out.println(&quot;&gt;&gt;&gt; &quot; + greeting.getGreeting());\n    }\n\n    // stop and unload all plugins\n    pluginManager.stopPlugins();\n    pluginManager.unloadPlugins();\n\n}\n</code></pre>\n<p>For further details please refer to the <a href="https://pf4j.org/" rel="noreferrer">documentation</a></p>\n'}]
['https://Stackoverflow.com/questions/60764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2443/']