Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Created June 27, 2017 11:47
Show Gist options
  • Save bdelacretaz/0d238aff34585c487a04395bacfc0781 to your computer and use it in GitHub Desktop.
Save bdelacretaz/0d238aff34585c487a04395bacfc0781 to your computer and use it in GitHub Desktop.
Inject Groovy expressions in a plain Java string
// 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