Swapnil Kotwal
Swapnil Kotwal

Reputation: 5730

Gradle task replace string in .java file not working

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?

Upvotes: 0

Views: 1148

Answers (2)

lance-java
lance-java

Reputation: 27994

By default, ReplaceTokens has beginToken='@' and endToken='@'. So change to

filter(ReplaceTokens, tokens: [
        "VERSION" : '1.0.0', 
        "PATCH_LEVEL" : '0.5',
        ...
    ])

Upvotes: 2

Swapnil Kotwal
Swapnil Kotwal

Reputation: 5730

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

Upvotes: 0

Related Questions