I\'d like to generate a Java class using a Gradle task for a Java project, similar to how the Android plugin creates BuildConfig.java
using the
More elegant approach is to write a Gradle Plugin.
task javaSourceGen(type: com.somecompany.gensrc.GenerateSouce) {
//pass appropriate parameters
}
compileJava.dependsOn(javaSourceGen)
Then in the Gradle Plugin, Any Java Source generator project can be used.
For ex: https://github.com/square/javapoet or http://codemodel.java.net/
I wrote a gradle plugin which aims to provide a build config like the one from android tooling gradle plugin for java/groovy projects:
https://github.com/mfuerstenau/gradle-buildconfig-plugin
It's per source set, because I needed a specific version to display for different artifacts relying on two different source sets.
just apply the plugin (gradle 2.1+)
plugins {
'de.fuerstenau.buildconfig'
}
buildConfig {
sourceSets {
// this is a build config for "main" source set
main {
// if not defined, these are the defaults
// packageName = project.group (not specified -> de.fuerstenau.buildconfig)
// appName = project.name
// version = project.version
// custom fields con also be added
// for example:
// buildConfigField "String" "MYSTRING" "value"
}
// add more or other sourceSets like "main", be aware
// of conflicts if you use
// them combined
}
}
will result in a class de.fuerstenau.buildconfig.BuildConfig
(package can be configured as above):
package de.fuerstenau.buildconfig;
public final class BuildConfig
{
private BuildConfig { }
public final String VERSION = "<whatever-version-was-configured>";
public final String NAME = "<whatever-appName-was-configured>";
}
Two tasks will be created and added, one to generate the class, the other to compile it, they execute before "compileJava"-task and the result is added as dependency.