Created
June 27, 2017 11:47
-
-
Save bdelacretaz/0d238aff34585c487a04395bacfc0781 to your computer and use it in GitHub Desktop.
Inject Groovy expressions in a plain Java string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Demonstrate how to inject Groovy expressions | |
// in a plain Java string | |
def now = "${new Date()}" | |
def data = [ value : "The date is ${now}" ] | |
// Inject Groovy variables from inputData | |
// into the supplied string | |
def interpolate(inputData, str) { | |
// TODO is there a way to have another name than "x" | |
// for the injected variable? | |
return Eval.x(inputData, "\"" + str.toString() + "\"") | |
} | |
// Use a plain Java String as input | |
def b = 'interpolated: ${x.value}.' | |
assert b.toString().contains("x.value") | |
assert b.getClass().getName().equals("java.lang.String") | |
// Interpolate and check | |
def expected = 'interpolated: The date is ' + now + '.' | |
println interpolate(data, b) | |
assert expected.toString().equals(interpolate(data, b).toString()) | |
println "Interpolation works as expected" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment