Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.gmail.plasmavn.enchantmentapi.services;
- import java.io.File;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.net.MalformedURLException;
- import java.net.URI;
- import java.net.URL;
- import java.net.URLClassLoader;
- import java.util.Enumeration;
- import java.util.Set;
- import java.util.jar.JarEntry;
- import java.util.jar.JarFile;
- import com.google.common.collect.Sets;
- public class ClassLoaderUtils {
- private static final Set<URL> loadedURL = Sets.newHashSet();
- @SuppressWarnings({ "resource", "unlikely-arg-type" })
- public static Set<Class<?>> loadClasses(File... files) throws MalformedURLException {
- Set<Class<?>> classes = Sets.newHashSet();
- for (File file : files) {
- if (file == null || !file.exists() || loadedURL.contains(file.toURI())) continue;
- URI uri = file.toURI();
- JarFile jarFile;
- try {
- jarFile = new JarFile(new File(uri.getPath()));
- } catch (IOException e) {
- System.out.println("Jar unknown: " + uri.toString());
- continue;
- }
- Set<String> preclasses = Sets.newHashSet();
- Enumeration<JarEntry> e = jarFile.entries();
- while (e.hasMoreElements()) {
- JarEntry je = e.nextElement();
- if (je.isDirectory() || !je.getName().endsWith(".class"))
- continue;
- String className = je.getName().substring(0, je.getName().length() - 6).replace('/', '.');
- preclasses.add(className);
- }
- if (preclasses.isEmpty()) {
- System.out.println("Empty name");
- continue;
- }
- addURL(uri.toURL());
- for (String clazz : preclasses) {
- try {
- Class<?> c = ClassLoaderUtils.class.getClassLoader().loadClass(clazz);
- classes.add(c);
- } catch (ClassNotFoundException ex) {
- Utils.debug("Fail on load class", ex);
- continue;
- }
- }
- }
- return classes;
- }
- private static void addURL(URL u) {
- URLClassLoader sysloader = (URLClassLoader) ClassLoaderUtils.class.getClassLoader();
- Class<?> sysclass = URLClassLoader.class;
- try {
- Method method = sysclass.getDeclaredMethod("addURL", URL.class);
- method.setAccessible(true);
- method.invoke(sysloader, u);
- loadedURL.add(u);
- } catch (Throwable t) {
- Utils.debug("Error, could not add URL to system classloader", t);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment