[java] Adding files to java classpath at runtime

Is it possible to add a file (not necessarily a jar file) to java classpath at runtime. Specifically, the file already is present in the classpath, what I want is whether I can add a modified copy of this file to the classpath.

Thanks,

This question is related to java runtime classpath

The answer is


Yes I believe it's possible but you might have to implement your own classloader. I have never done it but that is the path I would probably look at.


My solution:

File jarToAdd = new File("/path/to/file");

new URLClassLoader(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()) {
    @Override
    public void addURL(URL url) {
         super.addURL(url);
    }
}.addURL(jarToAdd.toURI().toURL());

The way I have done this is by using my own class loader

URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);

And create the following class:

public class DynamicURLClassLoader extends URLClassLoader {

    public DynamicURLClassLoader(URLClassLoader classLoader) {
        super(classLoader.getURLs());
    }

    @Override
    public void addURL(URL url) {
        super.addURL(url);
    }
}

Works without any reflection


You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.


You coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.


Try this one on for size.

private static void addSoftwareLibrary(File file) throws Exception {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}

This edits the system class loader to include the given library jar. It is pretty ugly, but it works.


yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to runtime

how can I debug a jar at runtime? How to check whether java is installed on the computer Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required) Excel VBA Run-time error '424': Object Required when trying to copy TextBox Execute external program An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module Error when checking Java version: could not find java.dll Change the location of an object programmatically java.lang.NoClassDefFoundError: Could not initialize class XXX How permission can be checked at runtime without throwing SecurityException?

Examples related to classpath

spark submit add multiple jars in classpath How to resolve this JNI error when trying to run LWJGL "Hello World"? Intellij Cannot resolve symbol on import Eclipse error "Could not find or load main class" "Could not find or load main class" Error while running java program using cmd prompt Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger getting JRE system library unbound error in build path Run a JAR file from the command line and specify classpath How do I resolve ClassNotFoundException? File inside jar is not visible for spring