2016-07-20 59 views
0

如何使用Java獲取當前項目的依賴關係? 我嘗試在Java類此代碼,但結果是空的:如何獲得依賴性gradle Java

class Example implements Plugin<Project> { 
    void apply(Project project) { 
      project.getConfigurations().getByName("runtime").getAllDependencies();   
     } 
    } 

謝謝您的回答JBirdVegas。我試着寫上您的Java例如:

List<String> deps = new ArrayList<>(); 
     Configuration configuration = project.getConfigurations().getByName("compile"); 
     for (File file : configuration) { 
      deps.add(file.toString()); 
     } 

但有錯誤:

Cannot change dependencies of configuration ':compile' after it has been resolved. 

運行時gradle這個構建

回答

2

你只是缺少一個步驟,文盲在發現依賴性

Groovy:

class Example implements Plugin<Project> { 
    void apply(Project project) { 
     def configuration = project.configurations.getByName('compile') 
     configuration.each { File file -> 
      println "Found project dependency @ $file.absolutePath" 
     }  
    } 
} 

的Java 8:

import org.gradle.api.Plugin; 
import org.gradle.api.Project; 
import org.gradle.api.artifacts.Configuration; 

public class Example implements Plugin<Project> { 
    @Override 
    public void apply(Project project) { 
     Configuration configuration = project.getConfigurations().getByName("compile"); 
     configuration.forEach(file -> { 
      project.getLogger().lifecycle("Found project dependency @ " + file.getAbsolutePath()); 
     }); 
    } 
} 

的Java 7:

import org.gradle.api.Plugin; 
import org.gradle.api.Project; 
import org.gradle.api.artifacts.Configuration; 

import java.io.File; 

public class Example implements Plugin<Project> { 
    @Override 
    public void apply(Project project) { 
     Configuration configuration = project.getConfigurations().getByName("compile"); 
     for (File file : configuration) { 
      project.getLogger().lifecycle("Found project dependency @ " + file.getAbsolutePath()); 
     } 
    } 
} 
+0

我所著我的問題的機構)) – dmitryZaskovich

+1

@dmitryZaskovich它不是必要的示例代碼回答你的答案代碼添加到您的問題。相反,選擇正確的答案。 – JBirdVegas

+0

回答時有錯誤,當我在java上使用它時( 我的java實現是錯誤的? – dmitryZaskovich