add Jar To Class Path - Java Reflection

Java examples for Reflection:Jar

Description

add Jar To Class Path

Demo Code


//package com.java2s;

import java.io.IOException;

import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void addJarToClassPath(URL[] urls) throws Exception {
        URLClassLoader sysloader = (URLClassLoader) ClassLoader
                .getSystemClassLoader();
        java.lang.Class<URLClassLoader> sysclass = URLClassLoader.class;
        java.lang.Class<?>[] parameters = new java.lang.Class<?>[] { URL.class };
        try {//from  w ww.j  a v  a 2  s  .c  o  m
            java.lang.reflect.Method method = sysclass.getDeclaredMethod(
                    "addURL", parameters);
            method.setAccessible(true);
            for (URL url : urls) {
                method.invoke(sysloader, new Object[] { url });
            }
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException(
                    "Error, could not add URL to system classloader");
        }// end try catch
    }
}

Related Tutorials