The ErsatzLisp Java Reflection API

As Ersatz Lisp (available in the "ersatz/" directory in the Picolisp release, or as a separate tarball) is completely written in Java, it comes with a set of dedicated functions to interface to the Java Reflection API.

The central function is java. It comes in four forms:

(java 'cls 'T ['any ..]) -> obj

Constructor call, returning a Java object. cls is the name of a Java class. The optional any arguments are passed to the Java constructor.

(java 'cls 'msg ['any ..]) -> obj

Calls a static method msg for a class cls.

(java 'obj 'msg ['any ..]) -> obj

Calls a dynamic method msg for an object obj.

The optional any arguments to the above three forms can be (java 'obj ['cnt]) -> any

Converts a Java object to the corresponding Lisp type. Supported types, and their conversion results are:

Example:
   : (setq Sb (java "java.lang.StringBuilder" T "abc"))
   -> $StringBuilder
   : (java Sb "append" (char: 44))
   -> $StringBuilder
   : (java Sb "append" 123)
   -> $StringBuilder
   : (java Sb "toString")
   -> $String
   : (java @)
   -> "abc,123"
   : (setq S (java "java.lang.String" T "abcde"))
   -> $String
   : (java (java S "getBytes"))
   -> (97 98 99 100 101)
   : (java "java.lang.String" T (mapcar byte: (100 101 102)))
   -> $String
   : (java @)
   -> "def"


To access public fields in Java objects or classes, public can be used:

(public 'obj 'any ['any ..]) -> obj

Returns the value of a public field any in object obj.

(public 'cls 'any ['any ..]) -> obj

Returns the value of a public field any in class cls.

In both forms, the optional any arguments will in turn access corresponding fields in the object retrieved so far.

Example:
   : (public "java.lang.System" "err")
   -> $PrintStream
   : (java @ "println" "Hello world")
   Hello world
   -> NIL


To create an interface object:

(interface 'cls|lst 'sym 'fun ..) -> obj

Creates an interface, i.e. a set of methods for a class cls (or a list of classes lst).

Example:
   #!ersatz/pil
   (let
      (Frame (java "javax.swing.JFrame" T "Bye-Frame")
         Button (java "javax.swing.JButton" T "OK") )
      (java Frame "add" "South" Button)
      (java Button "addActionListener"
         (interface "java.awt.event.ActionListener"  # When button is clicked,
            'actionPerformed '((Ev) (bye)) ) )       # Exit PicoLisp
      (java Frame "setSize" 100 60)
      (java Frame "setVisible" T) )


Finally, we have a set of type conversion functions, to produce Java objects from Lisp data: For a more elaborated example, take a look at the article Swing REPL written in Ersatz PicoLisp.

https://picolisp.com/wiki/?ersatzreflection

10feb13   abu