org.openxma.dsl.common.jdt.ChildFirstUrlClassloader Maven / Gradle / Ivy
package org.openxma.dsl.common.jdt;
import java.net.URL;
import java.net.URLClassLoader;
public class ChildFirstUrlClassloader extends URLClassLoader {
private final String[] childFirstClassName;
private final String[] childFirstResourceName;
private final String[] childFirstResourceSuffix;
private final ClassLoader parent;
public ChildFirstUrlClassloader(URL[] urls, ClassLoader parent, String[] childFirstClassName,
String[] childFirstResourceName, String[] childFirstResourceSuffix) {
super(urls, parent);
this.parent = parent;
this.childFirstClassName = childFirstClassName;
this.childFirstResourceName = childFirstResourceName;
this.childFirstResourceSuffix = childFirstResourceSuffix;
}
protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class> clazz = findLoadedClass(name);
if (clazz != null) {
return clazz;
}
boolean childFirst = isChildFirstClass(name);
ClassNotFoundException cnfe = null;
if (childFirst) {
try {
clazz = findClass(name);
} catch (ClassNotFoundException e) {
// continue
cnfe = e;
}
}
if (clazz == null) {
try {
clazz = parent.loadClass(name);
} catch (ClassNotFoundException e) {
// continue
}
}
if (clazz == null && cnfe != null) {
throw cnfe;
}
if (clazz == null && !childFirst) {
clazz = findClass(name);
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
public URL getResource(String name) {
URL url = null;
boolean childFirst = isChildFirstResource(name);
if (childFirst) {
url = findResource(name);
}
if (url == null) {
url = super.getResource(name);
}
return url;
}
private boolean isChildFirstClass(String name) {
for (int i = childFirstClassName.length - 1; i >= 0; i--) {
if (name.startsWith(childFirstClassName[i])) {
return true;
}
}
return false;
}
private boolean isChildFirstResource(String name) {
for (int i = childFirstResourceName.length - 1; i >= 0; i--) {
if (name.startsWith(childFirstResourceName[i])) {
return true;
}
}
for (int i = childFirstResourceSuffix.length - 1; i >= 0; i--) {
if (name.endsWith(childFirstResourceSuffix[i])) {
return true;
}
}
return false;
}
}