如何让依赖关系克服Java

时间:2016-07-20 15:40:13

标签: java gradle gradle-plugin

如何使用Java获取当前项目的依赖关系? 我在Java类中尝试此代码,但结果为空:

mx_speed01

感谢您的回答JBirdVegas。我尝试在Java上编写你的例子:

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

但有错误:

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

运行gradle build

1 个答案:

答案 0 :(得分:5)

您只是错过了迭代找到的依赖项的步骤

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());
        }
    }
}