I want to create dynamically a classloader for executing JSR223 script in a controlled environment but failing,
I'm trying remove/add jars using current(parent) ClassLoader, I tried solution Dynamically removing jars from classpath
public class DistributionClassLoader extends ClassLoader { public DistributionClassLoader(ClassLoader parent) { super(parent); } private Map<String, ClassLoader> classLoadersByDistribution = Collections.synchronizedMap(new WeakHashMap<>()); private final AtomicReference<String> distribution = new AtomicReference<>(); @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { final ClassLoader delegate = classLoadersByDistribution.get(distribution.get()); if (delegate != null) return Class.forName(name, true, delegate); throw new ClassNotFoundException(name); } public void addDistribution(String key, ClassLoader distributionClassLoader){ classLoadersByDistribution.put(key,distributionClassLoader); } public void makeDistributionActive(String key){distribution.set(key);} public void removeDistribution(String key){ final ClassLoader toRemove = classLoadersByDistribution.remove(key); } }
But it didn't include all my jars, in test this work
ClassLoader cl = this.getClass().getClassLoader();
Class cls = cl.loadClass("org.springframework.http.HttpStatus");
But using the solution doesn't find class
ClassLoader cl = new DistributionClassLoader(this.getClass().getClassLoader());
Class cls = cl.loadClass("org.springframework.http.HttpStatus");
Exception:
java.lang.ClassNotFoundException: org.springframework.http.HttpStatus
at com.DistributionClassLoader.loadClass(DistributionClassLoader.java:24)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
How can I select specific jars to add or remove from ClassLoader?
EDIT
I'm able to load jars using @czdepski answer but I still want to remove all/most classes except JDK's
Method sysMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); sysMethod.setAccessible(true); sysMethod.invoke(sysLoader, new Object[]{url});