Gradle - Groovy and Java class dependency - Compile

前端 未结 1 1572
死守一世寂寞
死守一世寂寞 2020-12-30 05:44

My project has both Java (N files) and Groovy code (1 file only). Java compile depends upon this single Groovy file\'s class file for Java compilation (compileJava task to s

相关标签:
1条回答
  • 2020-12-30 06:37

    The Groovy (base) plugin makes GroovyCompile tasks depend on the corresponding JavaCompile tasks because it's more common to call from Groovy into Java than the other way around. If you need it the other way around (or both ways), joint compilation is a good solution. Here is a somewhat improved (over your version) joint compilation setup:

    sourceSets {
        main {
            groovy {
                // override the default locations, rather than adding additional ones
                srcDirs = ['src/groovy', 'src/java'] 
            }
            java {
                srcDirs = [] // don't compile Java code twice 
            }
        }
    }
    

    If you prefer separate compilation with Java->Groovy dependencies only, something like the following should work:

    // since you aren't using the default locations
    sourceSets {
        main {
            groovy {
                srcDirs = ['src/groovy']
            }
            java {
                srcDirs = ['src/java']
            }
        }
    }
    
    // remove GroovyCompile->JavaCompile task dependencies
    tasks.withType(GroovyCompile) {
        dependsOn = [] 
    }
    
    // add JavaCompile->GroovyCompile task dependencies
    tasks.withType(JavaCompile) { task ->  
        dependsOn task.name.replace("Java", "Groovy")
    }
    

    Because a JavaCompile task and its corresponding GroovyCompile task write to the same output directory, Java compilation will now have the compiled Groovy code on its compile class path.

    PS: Calling a task from another task is not supported, and bad things can happen if you try. Instead, you should always work with task relationships (dependsOn, finalizedBy, mustRunAfter, shouldRunAfter).

    0 讨论(0)
提交回复
热议问题