43.8.1 Jasper Method Call Example

We begin with a small example.

                             
// Simple.java
import se.sics.jasper.*; public class Simple { private String instanceDatum = "this is instance data"; static int simpleMethod(int value) { return value*42; } public String getInstanceData(String arg) { return instanceDatum + arg; } }

Compile Simple.java (UNIX):

     % javac -deprecation \
       -classpath <installdir>/lib/sicstus-3.12.11/bin/jasper.jar Simple.java

Under Windows this may look like (the command should go on a single line):

     C:\> c:\jdk1.2.2\bin\javac -deprecation
      -classpath "D:\Program Files\SICStus Prolog VC10 3.12.11\bin\jasper.jar" Simple.java

The option `-deprecation' is always a good idea, it makes javac warn if your code use deprecated methods.

                                
% simple.pl
:- use_module(library(jasper)). main :- %% Replace '/my/java/dir' below with the path containing %% 'Simple.class', e.g. to look in the current directory use %% classpath(['.']). %% You can also use the CLASSPATH environment variable and call %% jasper_initialize(JVM) %% Under Windows it may look like classpath(['C:/MyTest']) jasper_initialize([classpath(['/my/java/dir'])],JVM), format('Calling a static method...~n',[]), jasper_call(JVM, method('Simple','simpleMethod',[static]), % Which method simple_method(+integer,[-integer]), % Types of arguments simple_method(42,X)), % The arguments. format('simpleMethod(~w) = ~w~n',[42,X]), format('Creating an object...~n',[]), jasper_new_object(JVM, 'Simple', init, init, Object), format('Calling an instance method on ~w...~n',[Object]), jasper_call(JVM, method('Simple','getInstanceData',[instance]), %% first arg is the instance to call get_instance_data(+object('Simple'), +string,[-string]), get_instance_data(Object, 'foobar', X1)), format('getInstanceData(~w) = ~w~n',['foobar',X1]).

Then, run SICStus:

     % echo "[simple],main." | sicstus
     SICStus 3.12.11 ...
     Licensed to SICS
     % consulting /home1/jojo/simple.pl...
     [...]
     % consulted /home1/jojo/simple.pl in module user, 100 msec 26644 bytes
     Calling a static method...
     simpleMethod(42) = 1764
     Creating an object...
     Calling and instance method on $java_object(135057576)...
     getInstanceData(foobar) = this is instance datafoobar

This example performed three things.