How to add gradle generated source folder to Eclipse project?

邮差的信 提交于 2019-12-03 12:37:21
Andreas Schmid

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'.

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.

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)
  }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!