英文:
Gradle task replace string in .java file not working
问题
我有下面的 VersionConstants.java 文件:
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@";
}
我按照这里的回答 https://stackoverflow.com/a/33475075/1665592 进行了操作,尝试如下:
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',
        ...
    ])
}
但是,它只是复制了 VersionConstants.java 文件本身,并没有将关键字替换为所需的值,即 1.0.0 或 0.5 等。
为什么会这样?
英文:
I've below VersionConstants.java file..
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@";
}
I followed this answer from here https://stackoverflow.com/a/33475075/1665592 and tried as
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',
        ...
    ])
}
but, it is coping VersionConstants.java file as it is and not replacing the keywords with desired values i.e. 1.0.0 or 0.5 etc.
Why?
答案1
得分: 2
默认情况下,ReplaceTokens的beginToken为'@',endToken为'@'。所以更改为
filter(ReplaceTokens, tokens: [
        "VERSION" : '1.0.0', 
        "PATCH_LEVEL" : '0.5',
        ...
    ])
英文:
By default, ReplaceTokens has beginToken='@' and endToken='@'. So change to
filter(ReplaceTokens, tokens: [
        "VERSION" : '1.0.0', 
        "PATCH_LEVEL" : '0.5',
        ...
    ])
答案2
得分: 0
明白,我刚刚将@VERSION@替换为VERSION,它就像魔法般地正常工作了!
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',
        ...
    ])
}
英文:
Got it, I just replaced @VERSION@ with VERSION and it work like a charm!
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',
        ...
    ])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论