Class Path Tour

In this guide we want to show how the runtime library can be connected with Java code. We will step by step show how a Java foreign predicate can be created and executed that will hello an argument. The Jekejeke Prolog runtime library does as well not provide an editor for Java classes. Again we have to refer to the given computing environment. We create the following Java class:

Picture 5: Creating a Java Class Source

The Java class provides a Java method hello. This method hellos the given argument on the output stream of the given interpreter. To be able to compile the java class the Jekejeke Prolog runtime library has to be present. For more details on compiling with the runtime library see the installation guide. When successful the Java compiler will have created a byte code file Hello.class, which will contain the Java method hello.

We can now start the Jekejeke Prolog runtime library and try to access the Java method hello. We will try to declare a new user predicate hello/1, which will be defined via the Java method hello. Our attempt will terminate with an exception, since the file Hello.class is not known to the Jekejeke Prolog runtime library per se:

?- foreign(hello/1, 'Hello', hello('Interpreter', 'String')).
Error: Class 'Hello' not found.
foreign / 3

We can change the situation. We simply have to add the directory with the file Hello.class to the class path. This can be done via the class path dialog. Note the slash at the end of the path. It is needed, so that the class loader will know that the path points to a directory and not to an archive:

Picture 6: Setting the Class Path

After having changed the class path, we need to restart the Jekejeke Prolog runtime library. The declaration of the Java foreign predicate should then succeed. We can use the system predicate listing/0 to check whether the Java foreign predicate was added to the current knowledge base:

?- foreign(hello/1, 'Hello', hello('Interpreter', 'String')).
?- listing.
:- foreign(hello / 1, 'Hello', hello('Interpreter', 'String')).

The new predicate hello/1 will hello the given argument. Again we can test it directly in the console window of the runtime library:

?- hello('Anna').
Hello Anna
?- hello('Bert').
Hello Bert

Since the ISO core standard requires that the current output may also point to a binary stream, we cannot guarantee that it is of type Writer. The Java method for the hello predicate is thus not safe from class cast exceptions. Also the current code suppresses an eventual IOException thrown by the character output. The class Hello2 in the appendix shows an alternative implementation. The alternative code does check the type of the current output and it passes on an IOException in the form of an InterpreterMessage.