Default Classloader when executing ANT task

I have implemented a custom ANT task (extending org.apache.tools.ant.Task) which uses internally the context classloader from the current thread. (looks like this)

Thread.currentThread().getContextClassLoader()

If the task is executed for example via a random main method from any java class everything just works as expected. The problem is that if I build an jar, containing this task and everything it needs and define in anothers project build.xml a for my own task... then ANT seems to use its own classloader. This results in many problems, since the ANT classloader can´t know my classes.

Is there any workaround for this? Doing things like the following has not helped: (inside execute method of my task)

 Thread.currentThread()
       .setContextClassLoader(AnyOwnClass.class.getClassLoader());

Is it even possible to get the "real" classloader? Any help would be nice


有关详细信息,请参阅此问题,一种可能的解决方案可能是ant-classloader任务。


I also came across this class loading issue and after trying out various things for couple of days ended up creating a new class loader and setting it as the current class loader when executing my custom task.

        ClassLoader currentClazzLoader = Thread.currentThread().getContextClassLoader();
        try {
            ClassLoader customClazzLoader = ClasspathUtils.getUniqueClassLoaderForPath(getProject(), classpath, false);
            Thread.currentThread().setContextClassLoader(customClazzLoader);
            Class<?> clazz = customClazzLoader.loadClass("xxx");
            ....
            // use reflection to instantiate/call methods
            ....
        } catch (Exception e) {
            throw new BuildException(x);
        } finally {
            Thread.currentThread().setContextClassLoader(currentClazzLoader);
        }

My custom ant task accepted a nested 'classpath' element. This was passed as the 2nd arg to ClasspathUtils.getUniqueClassLoaderForPath method. This got rid of the below class loading problems I faced with velocity when invoked via Ant.

Caused by: java.lang.ClassNotFoundException: org.apache.velocity.tools.config.Data
       at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
       at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
       at java.security.AccessController.doPrivileged(Native Method)
       at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
       at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
       at org.apache.commons.digester.ObjectCreateRule.begin(ObjectCreateRule.java:205)
       at org.apache.commons.digester.Rule.begin(Rule.java:175)
       at org.apache.commons.digester.Digester.startElement(Digester.java:1453)
       ... 48 more

hope this helps.

链接地址: http://www.djcxy.com/p/7718.html

上一篇: 以编程方式使用Ant任务执行Ant脚本

下一篇: 执行ANT任务时的默认Classloader