How to add gradle generated source folder to Eclip

2019-03-27 02:58发布

问题:

My gradle project generates some java code inside gen/main/java using annotation processor. When I import this project into Eclipse, Eclipse will not automatically add gen/main/java as source folder to buildpath. I can do it manually. But is there a way to automate this?

Thanks.

回答1:

You can easily add the generated folder manually to the classpath by

eclipse {
    classpath {
        file.whenMerged { cp ->
            cp.entries.add( new org.gradle.plugins.ide.eclipse.model.SourceFolder('gen/main/java', null) )
        }
    }
}

whereby null as a second constructor arg means that Eclipse should put the compiled "class" files within the default output folder. If you want to change this, just provide a String instead, e.g. 'bin-gen'.



回答2:

I think it's a little bit cleaner just to add a second source directory to the main source set.

Add this to your build.gradle:

sourceSets {
    main {
        java {
            srcDirs += ["src/gen/java"]
        }
    }
}

This results in the following line generated in your .classpath:

<classpathentry kind="src" path="src/gen/java"/>

I've tested this with Gradle 4.1, but I suspect it'd work with older versions as well.



回答3:

Andreas' answer works if you generate Eclipse project from command line using gradle cleanEclipse eclipse. If you use STS Eclipse Gradle plugin, then you have to implement afterEclipseImport task. Below is my full working snippet:

project.ext {
  genSrcDir = projectDir.absolutePath + '/gen/main/java'
}
compileJava {
  options.compilerArgs += ['-s', project.genSrcDir]
}
compileJava.doFirst {
  task createGenDir << {
    ant.mkdir(dir: project.genSrcDir)
  }
  createGenDir.execute()
  println 'createGenDir DONE'
}
eclipse.classpath.file.whenMerged {
  classpath - >
    def genSrc = new org.gradle.plugins.ide.eclipse.model.SourceFolder('gen/main/java', null)
  classpath.entries.add(genSrc)
}
task afterEclipseImport(description: "Post processing after project generation", group: "IDE") {
  doLast {
    compileJava.execute()
    def classpath = new XmlParser().parse(file(".classpath"))
    new Node(classpath, "classpathentry", [kind: 'src', path: 'gen/main/java']);
    def writer = new FileWriter(file(".classpath"))
    def printer = new XmlNodePrinter(new PrintWriter(writer))
    printer.setPreserveWhitespace(true)
    printer.print(classpath)
  }
}