Java is trivial to call from Gosu. Just put Java JARs on the Gosu classpath, add Java class usage declaration and you are ready to go.
It is not so straightforward to do opposite, as Gosu relies on its own classloader which makes its magical tricks like Open Type System possible.
As Gosu's syntax is more powerful and less explicit than Java, wouldn't it be nice to be able to write at least parts of your application in it? Here is how you can do it.
General idea is to:
Both Gosu provider and Java consumer will share dependency on the interface defined in Java, which may be distributed as a separate JAR file.
Make sure your module SDKs are pointing to:
WARNING: I've been experiencing problems with IntelliJ Idea 12.1.6 while trying to make it run. Try your luck with IJ 12.1.4. This is what I used for this example.
This will contain definition of interface offered by our Gosu class. This will be shared between our Gosu provider and Java consumer code.
package sample.api;
public interface ServiceApi {
String execute();
}
Here we implement our logic in Gosu.
package sample.provider
uses sample.api.ServiceApi
class ServiceProvider implements ServiceApi {
construct() {
}
override function execute() : String {
return "Hello from Gosu service"
}
}
And this how we will initialize Gosu and then instantiate and call Gosu class providing implementation of known interface.
package sample.consumer;
import sample.api.ServiceApi;
import gw.lang.reflect.ReflectUtil;
import gw.lang.Gosu;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class ServiceConsumer {
public ServiceConsumer() {
}
public String consume() {
List gosuPath = new ArrayList();
// path to libraries
gosuPath.add(new File("c:/work/projects/sandbox/java-gosu-interop/lib/"));
// path to gosu sources
gosuPath.add(new File("c:/work/projects/sandbox/java-gosu-interop/gosu-provider/src/"));
Gosu.init(gosuPath);
ServiceApi service = (ServiceApi) ReflectUtil.construct("sample.provider.ServiceProvider");
return service.execute();
}
public static void main(String[] args) throws URISyntaxException {
ServiceConsumer consumer = new ServiceConsumer();
System.out.println(consumer.consume());
}
}
You should end up with something like this:
To run your Java ServiceConsumer which executes Gosu code:
You will find source code for this at GitHub.
Have fun.
CREDITS: