add Jar To Classpath - Java Reflection

Java examples for Reflection:Jar

Description

add Jar To Classpath

Demo Code


//package com.java2s;

import java.io.File;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void addJarToClasspath(File jarFile) {
        try {/*from w ww .  j av a  2 s . c o m*/
            URL url = jarFile.toURI().toURL();
            URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader
                    .getSystemClassLoader();
            Class<?> urlClass = URLClassLoader.class;
            Method method = urlClass.getDeclaredMethod("addURL",
                    new Class<?>[] { URL.class });
            method.setAccessible(true);
            method.invoke(urlClassLoader, new Object[] { url });
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Related Tutorials