Node:Jasper Method Call Example, Next:Jasper Library Predicates, Up:Jasper
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.9.1/bin/jasper.jar Simple.java
On 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\bin\jasper.jar" Simple.java
The flag -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) %% On 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 (if necessary with the -m
flag):
% echo "[simple],main." | sicstus -m SICStus 3.9 (x86-linux-glibc2): Fri Sep 24 17:43:20 CEST 1999 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 yes
This example performed three things.
simpleMethod
was called with argument '42', and
returned the square of '42', '1764'.
Simple
was created.
getInstanceData
was executed on the object just
created. The method took an atom as an argument and appended the atom to
a string stored as a field in the object, yielding "this is instance
datafoobar".