Does anyone know if it's possible to use the same class loader in a custom task part of a target called from within an <antcall ...> in the same project? I tried using inheritRefs for antcall and the custom task is refers to a project-scoped class-path definition and either uses a loaderref or not. The result is always the same - antcall spawns a new ClassLoader.
Here's my
test build script:
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="../.." default="all" name="myLoader">
<property environment="env"/>
<target name="all" depends="one"/>
<path id="myClassPath">
<fileset dir=".">
<include name="printCL.jar"/>
</fileset>
</path>
<taskdef name="printCL" classname="study.ant.PrintClassLoaderTask" loaderRef="myLoader">
<classpath refid="myClassPath"/>
</taskdef>
<target name="one">
<printCL name="One"/>
<antcall target="two" inheritRefs="true"/>
</target>
<target name="two">
<printCL name="Two"/>
<printCL name="Two 1/2"/>
</target>
</project>
My custom task looks like this:
package study.ant;
import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;
public class PrintClassLoaderTask extends Task {
public static int accCnt = 0;
private
String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void execute() throws BuildException {
synchronized (PrintClassLoaderTask.class) {
accCnt++;
}
System.out.println("Task: " + getName() + ", instance #" + accCnt);
System.out.println(
"ClassLoader: "
+ printClassLoader(PrintClassLoaderTask.class.getClassLoader())
+ "\n");
(new
IllegalStateException("Just printing stackTrace")).printStackTrace();
// log(
// "ClassLoader: "
// + printClassLoader(PrintClassLoaderTask.class.getClassLoader()));
}
public static String printClassLoader(ClassLoader cl) {
java.io.StringWriter sw = new java.io.StringWriter();
if (cl == null) {
return "[NULL]";
}
try {
doPrintClassLoader(cl, sw);
} catch (java.io.IOException ioExc) {
return cl.toString() + " (Error: " + ioExc + ")";
}
return sw.toString();
}
public static int doPrintClassLoader(ClassLoader cl, java.io.Writer w)
throws java.io.IOException {
int depth = 0;
ClassLoader parent = cl.getParent();
if (parent != null) {
depth = doPrintClassLoader(parent, w);
}
if (depth > 0) {
w.write("\n");
for (int i = 0; i < depth; i++) {
w.write(" ");
}
w.write(" -> ");
}
w.write("\"" + cl.toString() + "\"");
return ++depth;
}
}
Thank you in anticipation.