Cyrus' New Completely Useless Blog

Making new Java classes with ABCL

Armed Bear Common Lisp (ABCL) is an implementation of Common Lisp that runs on top of the JVM. One nice feature of this is that ABCL supports interoperability with java code so one can use java libraries from Common Lisp code.

One neat feature of ABCL is that you can create java classes directly in Common Lisp, in addition to just defining functions, lisp (CLOS) classes, generic functions, methods, etc...

Let's look at a toy example of creating a new java class:

;; let's define a new class
(defparameter *forty-two-class*
  (java:jnew-runtime-class
   "FortyTwo"
   :interfaces (list "java.lang.Comparable")
   :methods `(("compareTo" ,"java.lang.Integer" (,"java.lang.Integer")
               (lambda (this x)
                 (declare (ignore this))
                 (cond ((> 42 x) -1)
                       ((= 42 x) 0)
                       ((< 42 x) 1)
                       (t (error "bogus!"))))
               :modifiers (:public)))
   :access-flags '(:public :static :final)))

Now, from lisp, we can make a new instance of this java class as follows:

;; make an instance of it
(defparameter *forty-two* (java:jnew *forty-two-class*))

and we can call a method on it like so:

CL-USER> (java:jcall "compareTo" *forty-two* 43)
1

A trivial example, but I'll show some real world-examples of how this is useful in an upcoming post.