Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle difference between compileJava and tasks.withType(JavaCompile)

I'm currently trying to convert an old code base from Java 8 to Java 11. Part of this old code base uses some Java-internal classes (specifically sun.security.x509). In order to make this work in Java 11 I have to add the "add-exports" flag to my compileJava task in Gradle to allow this internal class to be visible outside its module.

So I started with this:

compileJava {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11

    options.compilerArgs = [ '--add-exports=java.base/sun.security.x509=ALL-UNNAMED' ]
}

This doesn't seem to work, as the add-exports does not get passed to javac, so my code fails to compile.

However, if I do this instead it works, properly passing the add-exports to the javac process.

tasks.withType (JavaCompile) {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11

        options.compilerArgs = [ '--add-exports=java.base/sun.security.x509=ALL-UNNAMED' ]
}

Obviously, there's something I don't understand here. These appear to me to functionally perform the same operations, yet the second works while the first one fails.

Can anyone enlighten me as to what the difference is, and why one works and the other fails?

like image 672
Steve Avatar asked Oct 11 '25 11:10

Steve


1 Answers

When you do:

compileJava {
    // configure...
}

You are configuring a specific task named compileJava that happens to have a type of JavaCompile. It will not configure any other tasks. But when you do:

withType(JavaCompile) {
    // configure...
}

You are configuring every task whose type is JavaCompile. This includes tasks like compileTestJava. Since you've confirmed1 that it's your test code that fails to compile with the first approach, that explains why the second approach solves the issue.


1. Comment quote: "And that explains it. The code that's failing to compile in in my test code. I assumed that the test code also compiled with compileJava, not compileTestJava. Since that;s not how it works, it makes sense my tests would fail to compile when augmenting compileJava. Thanks..."

like image 82
Slaw Avatar answered Oct 14 '25 02:10

Slaw