How do you change the CLASSPATH within Java?

How do you change the CLASSPATH of a Java process from within the Java process?


Before you ask me "Why would you want to do that?" I'll explain it shortly.

When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a Clojure source file, and I'd like to do it without having to restart Clojure itself (which is not really an option when using it on Slime on Emacs).

That's the reason but I don't want this question tagged as some-weird-language some-weird-editor and be disregarded by the majority of Java developers that may have the answer.


Asked by: Charlie694 | Posted: 23-01-2022






Answer 1

Update Q4 2017: as commented below by vda8888, in Java 9, the System java.lang.ClassLoader is no longer a java.net.URLClassLoader.

See "Java 9 Migration Guide: The Seven Most Common Challenges"

The class loading strategy that I just described is implemented in a new type and in Java 9 the application class loader is of that type.
That means it is not a URLClassLoader anymore, so the occasional (URLClassLoader) getClass().getClassLoader() or (URLClassLoader) ClassLoader.getSystemClassLoader() sequences will no longer execute.

java.lang.ModuleLayer would be an alternative approach used in order to influence the modulepath (instead of the classpath). See for instance "Java 9 modules - JPMS basics".


For Java 8 or below:

Some general comments:

you cannot (in a portable way that's guaranteed to work, see below) change the system classpath. Instead, you need to define a new ClassLoader.

ClassLoaders work in a hierarchical manner... so any class that makes a static reference to class X needs to be loaded in the same ClassLoader as X, or in a child ClassLoader. You can NOT use any custom ClassLoader to make code loaded by the system ClassLoader link properly, if it wouldn't have done so before. So you need to arrange for your main application code to be run in the custom ClassLoader in addition to the extra code that you locate.
(That being said, cracked-all mentions in the comments this example of extending the URLClassLoader)

And you might consider not writing your own ClassLoader, but just use URLClassLoader instead. Create a URLClassLoader with a url that are not in the parent classloaders url's.

URL[] url={new URL("file://foo")};
URLClassLoader loader = new URLClassLoader(url);

A more complete solution would be:

ClassLoader currentThreadClassLoader
 = Thread.currentThread().getContextClassLoader();

// Add the conf dir to the classpath
// Chain the current thread classloader
URLClassLoader urlClassLoader
 = new URLClassLoader(new URL[]{new File("mtFile").toURL()},
                      currentThreadClassLoader);

// Replace the thread classloader - assumes
// you have permissions to do so
Thread.currentThread().setContextClassLoader(urlClassLoader);

If you assume the JVMs system classloader is a URLClassLoader (which may not be true for all JVMs), you can use reflection as well to actually modify the system classpath... (but that's a hack;)):

public void addURL(URL url) throws Exception {
  URLClassLoader classLoader
         = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class clazz= URLClassLoader.class;

  // Use reflection
  Method method= clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
  method.setAccessible(true);
  method.invoke(classLoader, new Object[] { url });
}

addURL(new File("conf").toURL());

// This should work now!
Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");

Answered by: Kellan629 | Posted: 24-02-2022



Answer 2

I don't believe you can - the right thing to do (I believe) is create a new classloader with the new path. Alternatively, you could write your own classloader which allows you to change the classpath (for that loader) dynamically.

Answered by: Audrey381 | Posted: 24-02-2022



Answer 3

There's no need to write your own class loader! There's clojure.lang.DynamicClassLoader.

http://blog.japila.pl/2011/01/dynamically-redefining-classpath-in-clojure-repl/

Answered by: Tara679 | Posted: 24-02-2022



Answer 4

You may want to look into using java.net.URLClassLoader. It allows you to programmatically load classes that weren't originally in your classpath, though I'm not sure if that's exactly what you need.

Answered by: Hailey787 | Posted: 24-02-2022



Answer 5

It is possible as seen from the two links below, the method VonC gives seems to be the best but check out some of these posts and google for "Java Dynamic Classpath" or "Java Dynamic Class Loading" and find out some info from there.

I'd post in more depth but VonC has pretty much done the job.

From Dynamic loading of class and Jar files.

Also check this sun forum post.

Answered by: Adelaide233 | Posted: 24-02-2022



Answer 6

String s="java  -classpath abcd/ "+pgmname+" "+filename;   
Process pro2 = Runtime.getRuntime().exec(s); 
BufferedReader in = new BufferedReader(new InputStreamReader(pro2.getInputStream()));

is an example of changin the classpath in java program

Answered by: Lucas557 | Posted: 24-02-2022



Similar questions

java - Clojure Lein Classpath Woes

I have a Leiningen project.clj file as follows: (defproject insane-noises "1.0.0-SNAPSHOT" :description "FIXME: write description" :dependencies [[org.clojure/clojure "1.3.0"] [overtone "0.6.0"]] :source-paths ["/Volumes/ra...


java - How to remove classpath variables from WAS module

On our Dev box, our application module contains references to the file:/apps/WebSphere61/systemApps/isclite.ear/ jar files and classpath entries. On our Prod box, however, it only contains the jar file containing all of our required classes. On Dev, this is causing a problem when using apache-commons-fileuploader as these classes are also references in the systemApps jar. How can we remove the systemApps li...


java - Nested Folders in Eclipse Classpath

I'm trying to add two folders to my eclipse project's classpath, let's say Folder A and Folder B. B is inside A. Whenever I add A to the classpath <classpathentry kind="lib" path="/A"/> it works just fine, but I need to be able to access the files in B as well. Whenever I try to add <classpathentry kind="lib" path="/A/B"/> to the classpath, ...


java - Compile CLASSPATH in a Windows batchfile

On a Unix systems it's very easy to compile the CLASSPATH by using find: LIBDIR=`find lib/ -name \*.jar` for DIR in $LIBDIR: do CLASSPATH="$CLASSPATH:$DIR" done java -classpath $CLASSPATH com.example.MyClass What would be the aquivalent in a Windows batchfile?


java - What's the minimum classpath for an Axis2 client?

I want to build an Axis2 client (I'm only accessing a remote web service, I'm not implementing one!) with Maven2 and I don't want to add 21MB of JARs to my project. What do I have to put in my pom.xml to compile the code when I've converted the WSDL with ADB?


java - Specifying classpath for classes inside the JAR itself

If I have a class org.foobar.MyClass and want to put it in a JAR file, do I have to put it in the JAR's /org/foobar/ directory, or can I put it in /bin/org/foobar/ and somehow specify /bin/ as classpath inside the JAR itself?


windows - BAT file to create Java CLASSPATH

I want to distribute a command-line application written in Java on Windows. My application is distributed as a zip file, which has a lib directory entry which has the .jar files needed for invoking my main class. Currently, for Unix environments, I have a shell script which invokes the java command with a CLASSPATH created by appending all files in lib directory. How do I write a .BAT file with similar fu...


Setting classpath for a Java stored procedure in Oracle

I've got an Oracle 10g database, and I have a third-party jar file. I want to be able to run a SQL select query in my database that ultimately runs code in my third-party library to retrieve info for inclusion in a SQL result set. I see lots of tutorials on "Java stored procedures" and these seem to be a promising way to do this, but none seem to use third-party libraries, and I can't seem to figure out how to specify a ...


java - can't get the classpath right

i'm trying to compile this slick2d example (first one) but i can't get it to work. here's the code: import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException;...


java - adding classpath in linux

export CLASSPATH=.;../somejar.jar;../mysql-connector-java-5.1.6-bin.jar java -Xmx500m folder.subfolder../dit1/some.xml cd .. is the above statement for setting the classpath to already existing classpath in linux is correct or not


java - use eclipse classpath in ant tasks

I want to use Ant to deliver a JAR file, how can I use the Eclipse classpath in my Ant task? Greets, Tobias






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top