Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2012 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2716374 to your computer and use it in GitHub Desktop.
Save anonymous/2716374 to your computer and use it in GitHub Desktop.
Conditional delegation in a ClassLoader
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