Gradle从.tmpl文件生成Java源代码

huangapple go评论64阅读模式
英文:

Gradle generate java source code from .tmpl file

问题

使用Ant,我们生成一些包含大部分运行时生成信息的Java代码。

对于ant任务,我们使用下面的VersionConstants.tmpl文件,它生成以下内容:

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@";
}

使用这个文件,我们生成VersionConstants.java文件。我看到了这个问题https://stackoverflow.com/q/20104323/1665592,但是Gradle是否支持对此提供任何原生支持?

英文:

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 https://stackoverflow.com/q/20104323/1665592 but does Gradle support any native support for this?

答案1

得分: 3

据我了解,您正在寻找一种方法来通过某些值替换Java源文件中的标记;有许多Gradle插件可以实现这一点,以下是其中一个示例:
https://github.com/HexoMod-tools/gradle.replace.token.preprocessor.plugin;您也可以尝试直接在Gradle插件注册表中搜索,例如:https://plugins.gradle.org/search?term=replace。

英文:

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, e.g. https://plugins.gradle.org/search?term=replace

答案2

得分: 2

我甚至避免使用第三方插件,以下是我实现的方法:

任务 生成源码(type: 复制) {
    来自 'src/replaceme/VersionConstants.java'
     "$buildDir/generated-src"
    过滤(org.apache.tools.ant.filters.ReplaceTokens, tokens: [
        "VERSION" : '1.0.0',
        "PATCH_LEVEL" : '0.5',
        // ...
    ])
}
英文:

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',
        ...
    ])
}

huangapple
  • 本文由 发表于 2020年9月14日 18:26:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63882486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定