Skip to content

Instantly share code, notes, and snippets.

@culmat
Created April 4, 2016 17:06
Show Gist options
  • Save culmat/e950fd34a2a2c6d8f906c312dd39bf62 to your computer and use it in GitHub Desktop.
Save culmat/e950fd34a2a2c6d8f906c312dd39bf62 to your computer and use it in GitHub Desktop.
package common;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class JarFileLoader extends URLClassLoader {
public JarFileLoader() {
super(new URL[] {});
}
public JarFileLoader withFile(String jarFile) {
return withFile(new File(jarFile));
}
public JarFileLoader withFile(File jarFile) {
try {
addURL(new URL("jar:file://" + jarFile.getAbsolutePath() + "!/"));
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
return this;
}
public JarFileLoader withLibDir(String path) {
// JAVA 8 to the rescue ;-)
// stream(new File(path).listFiles(f -> f.getName().endsWith(".jar"))).forEach(this::withFile);
for (File jarFile : new File(path).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
})) {
withFile(jarFile);
}
return this;
}
}
@LeGrosWinnie
Copy link

LeGrosWinnie commented Sep 3, 2018

Line 30 for the J8 version it is : Stream.of(new File...);

And to make it work :

		String path = "libs";
		List<URL> urls = new ArrayList<URL>();
		Stream.of(new File(path).listFiles(f -> f.getName().endsWith(".jar"))).forEach(f -> {
			try {
				urls.add(f.toURI().toURL());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		});
		URLClassLoader child = new URLClassLoader(urls.toArray(new URL[urls.size()]));
		Class theClass = Class.forName("ClassToLoad", true, child);
		Method method = theClass .getDeclaredMethod("getInstance");
		final Object theClassInstance = method.invoke(theClass );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment