我有一个名为MyPlugin的自定义插件,它包含一个名为MyTask的自定义任务。我想让MyTask取决于compileJava。我试图给出MyTask.dependsOn(compileJava),但是上面写着Task called 'MyTask' is not existing。有什么办法吗?

MyPlugin.java

public class MyPlugin implements Plugin<Project> {
    public static final String TASK_NAME = "MyTask";

    @Override
    public void apply(Project project) {
        project.getExtensions().create(TASK_NAME, MyExtension.class);
        project.getTasks().create(TASK_NAME, MyTask.class);
    }
}

MyTask.java
public class MyTask extends DefaultTask {
    private MyExtension extension;

    @TaskAction
    public void myTask() {
        Project project = getProject();
        extension = project.getExtensions().findByType(MyExtension.class);
        PropertyManager propertyManager = new PropertyManager(project, extension);
        propertyManager.setProperties();
        System.out.println(extension.getValue());
    }

MyExtension.java
public class MyExtension {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

build.gradle
apply plugin: 'maven'
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'com.jfrog.bintray'

sourceCompatibility = 1.8

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile gradleApi()
}

repositories {
    mavenCentral()
}

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
    }
}

task copyLibs(type: Copy) {
    from configurations.runtime
    into "$projectDir/libs"
}

MyTask.dependsOn(copyLibs)  //not working
MyTask.dependsOn(compileJava)   //not working

最佳答案

你必须用

tasks.MyTask.dependsOn(copyLibs)
tasks.MyTask.dependsOn(compileJava)

因为您定义的任务对象不在copyLibs之类的当前范围内。但是您可以通过任务引用来访问它(请参阅:https://docs.gradle.org/current/dsl/org.gradle.api.Project.html)

10-07 15:38