How to Add A Jar File To Java System Classpath At Run-time | Eklavya Online

How to Add A Jar File To Java System Classpath At Run-time

This can be done by using a simple reflection API hack as demonstrated in below sample code. This example assumes you have a file “c:/Sample.txt” that is not already in class path and at run-time c:/ is added the System classpath and then Sample.txt is made available.

import java.io.File;

import java.io.InputStream;

import java.lang.reflect.Method;

import java.net.URL;

import java.net.URLClassLoader;

 

public class HackJavaClasspath {

 

public static void addURL(URL url) throws Exception {

URLClassLoader cl = (URLClassLoader) ClassLoader

.getSystemClassLoader();

Class clazz = URLClassLoader.class;

 

Method method = clazz.getDeclaredMethod(“addURL”,

new Class[] { URL.class });

method.setAccessible(true);

method.invoke(cl, new Object[] { url });

}

 

public static void main(String[] args) throws Exception {

//Add c: to the classpath

addURL(new File(“c:/”).toURI().toURL());

//Now load the file from new location

InputStream in = Thread.currentThread().getContextClassLoader()

.getResourceAsStream(“Sample.txt”);

System.out.println(in.available());

 

}

}

Running this java class prints the number of bytes available. This indicates the file is available for further processing.