Recipe: How to Use Lombok with Eclipse, Gradle and Javadocs?

Lombok makes Java great, gradle is awesome, flexible build tool, Eclipse makes development a lot easier, and Javadocs makes the world go around.

So, when I started a new project, I wanted to figure out how to combine all this magic. The attached buildscript file I wrote for this purpose is isolated from other project issues. Save it somewhere accessible and enable it usingapply from: "path/to/lombok.gradle"

/**
 * Project Lombok, Eclipse, Javadocs and Gradle
 */
// Doing this twice (once here, once in your main project) has no effect on Gradle, but 
// this script depends on the Java and Eclipse plugins
apply plugin: 'java'
apply plugin: 'eclipse'

// Create a configuration to hold the lombok jar as a dependency
configurations {
    lombok
}
// Add the lombok jar to the configuration
dependencies { 
    lombok 'org.projectlombok:lombok:+' 
}
// Add the lombok configuration to all of the compile classpaths
sourceSets.each{ sourceSet -> 
    sourceSet.compileClasspath += configurations.lombok
    sourceSet.ext.delombok = new File(buildDir, "generated-src/delombok/" + sourceSet.name);
}
// This task will download lombok and install it in your eclipse instance
task installLombok() {
    dependsOn configurations.lombok
} << {
    File jarFile = null;
    configurations.lombok.resolvedConfiguration.resolvedArtifacts.find {
        if ("lombok".equals(it.name)) {
            jarFile = it.file;
        }
    }
    javaexec {
        main="-jar"
        args = [
            jarFile,
            "install",
            "auto"
        ]
    }
}
// Install lombok into eclipse when you set up the project (optional line)
eclipseProject.dependsOn installLombok

// Javadoc doesn't handle lombok'd code, so we have to "delombok" it - that is, expand the 
// neat annotations so that Javadoc can do something with them.
task delombok() {
    dependsOn configurations.compile
    dependsOn configurations.lombok
} << {
    File jarFile = null;
    configurations.lombok.resolvedConfiguration.resolvedArtifacts.find {
        if ("lombok".equals(it.name)) {
            jarFile = it.file;
        }
    }
    sourceSets.each{ sourceSet ->
        def classPath = sourceSet.compileClasspath.files.join(";")
        def delombokPath = sourceSet.ext.delombok
        delombokPath.mkdirs();
        javaexec {
            main = "-jar"
            args jarFile, "delombok"
            if (!classPath.empty) {
                args "-c", classPath
            }
            args "-d", delombokPath
            args sourceSet.allJava.srcDirs
        }
    }
}

javadoc {
    dependsOn delombok
    // At your discretion; I actually use ext.apiDelombok in my case
    source = sourceSets.main.ext.delombok
}

      

+3


source to share





All Articles