How do I get IntelliJ to recognize gradle generated sources dir?

In my case, it didn't work unless I added the generate sources directory to both sourceDirs and generatedSourceDirs:

def generatedSourcesDir = file('src/generated/main/java')
idea {
  module {
    sourceDirs += generatedSourcesDir
    generatedSourceDirs += generatedSourcesDir
  }
}

in 2020 you probably did not refresh the project in IDEA

because it actually works oob.

30 mins of reading outdated solutions :(


I'll point out a solution by Daniel Dekany, from a Gradle discussion thread actually linking to this question. To quote:

apply plugin: "idea"
...
sourceSets.main.java.srcDir new File(buildDir, 'generated/javacc')
idea {
    module {
        // Marks the already(!) added srcDir as "generated"
        generatedSourceDirs += file('build/generated/javacc')
    }
}

Works well for me.


The code of this answer, rewritten using Kotlin DSL, will look like this:

plugins {
    idea
}

val generatedSourcesPath = file("out/production/classes/generated")

java.sourceSets["main"].java.srcDir(generatedSourcesPath)

idea {
    module {
        generatedSourceDirs.add(generatedSourcesPath)
    }
}