IsolatedClassloader extends URLClassLoader { @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> c = findLoadedClass(name); if (c == null) { try { if (getParent() != null && rules.canLoad(name)) { c = getParent().loadClass(name); } else { ClassLoader systemClassLoader = getSystemClassLoader(); if (systemClassLoader.getParent() != null) { systemClassLoader = systemClassLoader.getParent(); } c = systemClassLoader.loadClass(name); } } catch (ClassNotFoundException e) { c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } IsolatedClassloader(ClassLoader parent, ClassloadRules rules); @Override URL getResource(String name); @Override Enumeration<URL> getResources(String name);  }
@Test public void should_use_isolated_system_classloader_when_parent_is_excluded() throws ClassNotFoundException, IOException { thrown.expect(ClassNotFoundException.class); thrown.expectMessage("org.junit.Test"); assertThat(classLoader.loadClass("java.lang.String", false)).isNotNull(); classLoader.loadClass("org.junit.Test", false); classLoader.close(); }
@Test public void should_use_parent_to_load() throws ClassNotFoundException, IOException { ClassloadRules rules = mock(ClassloadRules.class); when(rules.canLoad("org.junit.Test")).thenReturn(true); classLoader = new IsolatedClassloader(getClass().getClassLoader(), rules); assertThat(classLoader.loadClass("org.junit.Test", false)).isNotNull(); }