/** * Adds the content pointed by the URL to the classpath during runtime. Uses reflection since * <code>addURL</code> method of <code>URLClassLoader</code> is protected. */ public static void addUrlToClassPath(URL url, ClassLoader classLoader) { try { ReflectUtil.invokeDeclared( URLClassLoader.class, classLoader, "addURL", new Class[] {URL.class}, new Object[] {url}); } catch (Exception ex) { throw new IllegalArgumentException("Add URL failed: " + url, ex); } }
/** * Finds and loads class on classpath even if it was already loaded. * * @param className class name to find * @param classPath classpath * @param parent optional parent class loader, may be <code>null</code> */ public static Class findClass(String className, URL[] classPath, ClassLoader parent) { URLClassLoader tempClassLoader = parent != null ? new URLClassLoader(classPath, parent) : new URLClassLoader(classPath); try { return (Class) ReflectUtil.invokeDeclared( URLClassLoader.class, tempClassLoader, "findClass", new Class[] {String.class}, new Object[] {className}); } catch (Throwable th) { throw new RuntimeException("Class not found: " + className, th); } }
/** * Defines a class from byte array into the specified class loader. Warning: this is a * <b>hack</b>! * * @param className optional class name, may be <code>null</code> * @param classData bytecode data * @param classLoader classloader that will load class */ public static Class defineClass(String className, byte[] classData, ClassLoader classLoader) { try { return (Class) ReflectUtil.invokeDeclared( ClassLoader.class, classLoader, "defineClass", new Class[] {String.class, byte[].class, int.class, int.class}, new Object[] { className, classData, Integer.valueOf(0), Integer.valueOf(classData.length) }); } catch (Throwable th) { throw new RuntimeException("Define class failed: " + className, th); } }