Search code examples
classconfigurationgradledependenciesclassloader

How can I create a ClassLoader from a custom configuration in gradle?


I have define a custom configuration and dependencies.

repositories {
    mavenCentral()
}
configurations {
    myConfig
}
dependencies {
    myConfig   'org.foo:foo:+'
}

How can I create ClassLoader to load a class dynamically?

task myTask {
    def classLoader = configurations.myConfig.????
    def foo = Class.forName( "org.foo.Foo", true, classLoader ).newInstance();
}

Solution

  • I found this solution now. I hope there is nicer solution.

    def classLoader = getClassLoader( configurations.myConfig )
    
    ClassLoader getClassLoader( Configuration config ) {
        ArrayList urls = new ArrayList()
        config.files.each { File file ->
            urls += file.toURI().toURL()
        }
        return new URLClassLoader( urls.toArray(new URL[0]) );
    }