astra.core.ASTRAClassLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of astra-interpreter Show documentation
Show all versions of astra-interpreter Show documentation
Core interpreter artifact for the ASTRA Language
package astra.core;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ASTRAClassLoader {
private static ASTRAClassLoader defaultClassLoader = new ASTRAClassLoader();
public static ASTRAClassLoader getDefaultClassLoader() {
return defaultClassLoader;
}
private List loaders = new LinkedList();
private Map classes = new HashMap();
{
loaders.add(ClassLoader.getSystemClassLoader());
}
public void registerClassLoader(ClassLoader loader) {
loaders.add(loader);
}
/**
* Loads the corrsponding astra class if it is not already loaded. if it is
* loaded, then it returns the current reference.
*
* @param url the url of the class to be loaded
* @return an {@link ASTRAClass} object representing the class associated with
* the url
* @throws ASTRAClassNotFoundException generated if the class does not exist
*/
public ASTRAClass loadClass(String url) throws ASTRAClassNotFoundException {
ASTRAClass clazz = classes.get(url);
if (clazz == null) {
Class> c = null;
for (ClassLoader loader : loaders) {
c = doLoadClass(loader, url);
if (c != null)
break;
}
if (c != null) {
try {
clazz = (ASTRAClass) c.getDeclaredConstructor(new Class[0]).newInstance(new Object[0]);
} catch (Exception e) {
throw new ASTRAClassNotFoundException("Could not load ASTRA class: " + url,e);
}
} else {
throw new ASTRAClassNotFoundException("Could not find ASTRA class: " + url);
}
classes.put(url, clazz);
}
return clazz;
}
public ASTRAClass loadClass(Class cls) throws ASTRAClassNotFoundException {
ASTRAClass clazz = classes.get(cls.getCanonicalName());
if (clazz == null) {
try {
clazz = (ASTRAClass) cls.getDeclaredConstructor(new Class[0]).newInstance(new Object[0]);
} catch (Exception e) {
throw new ASTRAClassNotFoundException("Could not load ASTRA class: " + cls.getCanonicalName(),e);
}
classes.put(cls.getCanonicalName(), clazz);
}
return clazz;
}
private Class> doLoadClass(ClassLoader loader, String url) {
try {
return loader.loadClass(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}