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.
Update 2023: as commented below by Holger
Update Q4 2017: as commented below by vda8888, in Java 9, the System
java.lang.ClassLoaderis no longer ajava.net.URLClassLoader.See "Java 9 Migration Guide: The Seven Most Common Challenges"
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.
A more complete solution would be:
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;)):