Generate a Java class using Gradle for Java plugin

后端 未结 2 1807
后悔当初
后悔当初 2020-12-30 01:59

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

相关标签:
2条回答
  • 2020-12-30 02:26

    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/

    0 讨论(0)
  • 2020-12-30 02:36

    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.

    0 讨论(0)
提交回复
热议问题