We begin with a small example.
// Simple.javaimport 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-4.1.2/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 4.1.2\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 4.1.2 ... 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.
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".