2015-04-03 93 views
3

我已經定義了一個自定義配置和依賴關係。如何從gradle中的自定義配置創建ClassLoader?

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

如何創建ClassLoader來動態加載類?

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

你想在這裏完成什麼?你想動態地將類加載到你的Gradle構建腳本中嗎?爲什麼?難道你不能只使用常規的'buildscript'模塊來配置你的構建腳本的類路徑嗎? – Jolta 2015-04-03 20:12:29

+0

@Jolta這些類僅用於某些可選任務。對於默認構建,必須100%確定沒有依賴關係。我使用其他配置。 – Horcrux7 2015-04-05 08:12:56

回答

6

我現在發現了這個解決方案。我希望有更好的解決方案。

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])); 
} 
相關問題