Created
May 17, 2012 04:31
-
-
Save anonymous/2716374 to your computer and use it in GitHub Desktop.
Conditional delegation in a ClassLoader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConditionalDelegationClassLoader extends URLClassLoader | |
{ | |
private final String parentPrefix; | |
private final String childPrefix; | |
public ConditionalDelegationClassLoader(URL[] urls, String parentPrefix, String childPrefix) | |
{ | |
super(urls); | |
this.parentPrefix = parentPrefix; | |
this.childPrefix = childPrefix; | |
} | |
@Override | |
public Class<?> loadClass(String name) throws ClassNotFoundException | |
{ | |
Class<?> c = findLoadedClass(name); | |
if (c == null) | |
{ | |
boolean parentFirst = (parentPrefix == null || name.startsWith(parentPrefix)) && // load from parent | |
(childPrefix == null || !name.startsWith(childPrefix)); // don't load from child | |
if (parentFirst) | |
{ | |
try | |
{ | |
c = super.loadClass(name); | |
} | |
catch (ClassNotFoundException e) | |
{ | |
} | |
} | |
if (c == null) | |
{ | |
try | |
{ | |
c = findClass(name); | |
} | |
catch (ClassNotFoundException e) | |
{ | |
if (parentFirst) | |
{ | |
throw e; // we didn't find it in the parent or the child | |
} | |
else | |
{ | |
c = super.loadClass(name); // load from the parent now | |
} | |
} | |
} | |
} | |
return c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment