1

In What JVM-based scripting language support @WebService to create services at runtime? I was suggested to use Groovy to provide web services configured in a script read in at runtime.

To make this work with our existing infrastructure I need essentially to be able to add new entries to a List<Callable<String>> which I then can ask an executor to invokeAny upon.

The basic structure will be something like:

  • Groovy is embedded using GroovyScriptEngine
  • Initial list passed in from Java as "l" in the Binding passed in.
  • Groovy script defines and instantiates N objects, all implementing Callable<String> and add them to the list.
  • Back in Java the list is then further processed and then passed to the executor.

My initial feeble steps show that I will most likely need to use def c = { ... } as Callable<String> but then I get a ClassCastException. Reading up I see that it appears that this is a bit hard and involves closures.

What is the correct way to define and instantiate an object in Groovy which implements Callable<String>?

Community
  • 1
  • 1
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • What version of Groovy are you using? Closure already implements Callable in Groovy 1.8 and later. – Ian Roberts Sep 18 '12 at 10:18
  • @IanRoberts I pulled in groovy-all-1.0-jsr-05 from Maven which appeared to be the newest. `org.codehaus.groovy.runtime.InvokerHelper.getVersion()` reports "1.0-jsr-05". SHould I be using something else? – Thorbjørn Ravn Andersen Sep 18 '12 at 10:23
  • 1
    That's pretty ancient TBH. [`org.codehaus.groovy:groovy-all:2.0.2`](http://search.maven.org/#artifactdetails%7Corg.codehaus.groovy%7Cgroovy-all%7C2.0.2%7Cjar) is the latest. – Ian Roberts Sep 18 '12 at 10:25
  • I updated and now the script works. Could you please post an answer I can accept? – Thorbjørn Ravn Andersen Sep 18 '12 at 10:32

1 Answers1

2

In Groovy 1.8 and later, groovy.lang.Closure implements Callable by default so you don't need any "as" magic., simply:

l << { "hello" }
l << { "world" }

For earlier versions of Groovy (1.6 and 1.7 certainly, not sure about "ancient" versions) you need to use as:

import java.util.concurrent.Callable

l << ({ "hello" } as Callable)
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183