简体   繁体   中英

Gradle generate java source code from .tmpl file

Using Ant we generate some Java Code which mostly have some Runtime generated information.

for ant task we use below VersionConstants.tmpl file and it generates the

public class VersionConstants {

    /**
     * This class does not need to be instantiated.
     */
    private VersionConstants() { }


    public static final String VERSION = "@VERSION@";

    public static final String PATCH_LEVEL = "@PATCH_LEVEL@";

    public static final String REVISION = "@REVISION@";

    public static final String BUILDTIME = "@BUILDTIME@";

    public static final String BUILDHOST = "@BUILDHOST@";
}

using this we generate VersionConstants.java file. I saw this question Generate a Java class using Gradle for Java plugin but does Gradle support any native support for this?

As far as I understand, you are looking for a way to replace tokens in java source file by some values; there are plenty of gradle plugins that can do so, here's one of the examples: https://github.com/HexoMod-tools/gradle.replace.token.preprocessor.plugin; you may try to search directly in gradle plugins registry, eg https://plugins.gradle.org/search?term=replace

I even avoided third party plugins and achieved it as below

task generateSources(type: Copy) {
    from 'src/replaceme/VersionConstants.java'
    into "$buildDir/generated-src"
    filter(org.apache.tools.ant.filters.ReplaceTokens, tokens: [
        "VERSION" : '1.0.0', 
        "PATCH_LEVEL" : '0.5',
        ...
    ])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM