// create temp directory for classes
String tmpdir = System.getProperty("java.io.tmpdir");
File classDir = new File(new File(tmpdir), "classes" + hashCode() + System.currentTimeMillis());
if (!classDir.mkdir()) {
throw new BuildException("Could not create output directory.");
}
try {
// class loader used to compile classes
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) classLoader = getClass().getClassLoader();
// compile classes
compile(sources, classDir, classLoader);
// load classes
Thread.currentThread().setContextClassLoader(classLoader);
URLClassLoader cl = new URLClassLoader(new URL[]{classDir.toURL()}, classLoader);
List<String> failedToLoad = new ArrayList<String>();
for (String className : sources.keySet()) {
try {
cl.loadClass(className);
} catch (ClassNotFoundException e) {
failedToLoad.add(className);
}
}
if (!failedToLoad.isEmpty()) {
throw new BuildException("Could not load generated classes " + failedToLoad);
}
return cl;
} catch (IOException e) {
throw new BuildException(e);
} finally {
// clean up the temp directory
Util.delete(classDir);
}
}