source: trunk/abcl/src/org/armedbear/lisp/java.lisp @ 13369

Last change on this file since 13369 was 13369, checked in by Mark Evenson, 10 years ago

Make JAVA:ADD-TO-CLASSPATH a generic function.

With this change we can customize the mechanism for changing the
classpath. The first planned use is for JSS to use an :after method
to be informed of classpath additions, so we can factor out the ASDF
portion into the ABCL-ASDF extension package.

Add JAVA:GET-CURRENT-CLASSLOADER to access a wrapped instance of the
underlying current JVM classloader being used by ABCL.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 21.1 KB
Line 
1;;; java.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves, Andras Simon
4;;; $Id: java.lisp 13369 2011-07-01 14:00:27Z mevenson $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package "JAVA")
33
34(require "CLOS")
35(require "PRINT-OBJECT")
36
37(defvar *classloader* (get-default-classloader))
38
39(defun add-url-to-classpath (url &optional (classloader *classloader*))
40  (jcall "addUrl" classloader url))
41
42(defun add-urls-to-classpath (&rest urls)
43  (dolist (url urls)
44    (add-url-to-classpath url)))
45
46(defgeneric add-to-classpath (jar-or-jars &optional classloader))
47
48(defmethod add-to-classpath (jar-or-jars &optional (classloader (get-current-classloader)))
49  (%add-to-classpath jar-or-jars classloader))
50
51(defun jregister-handler (object event handler &key data count)
52  (%jregister-handler object event handler data count))
53
54(defun jinterface-implementation (interface &rest method-names-and-defs)
55  "Creates and returns an implementation of a Java interface with
56   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
57
58   INTERFACE is either a Java interface or a string naming one.
59
60   METHOD-NAMES-AND-DEFS is an alternating list of method names
61   (strings) and method definitions (closures).
62
63   For missing methods, a dummy implementation is provided that
64   returns nothing or null depending on whether the return type is
65   void or not. This is for convenience only, and a warning is issued
66   for each undefined method."
67  (let ((interface (jclass interface))
68        (implemented-methods
69         (loop for m in method-names-and-defs
70           for i from 0
71           if (evenp i)
72           do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
73           else
74           do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
75    (loop for method across
76      (jclass-methods interface :declared nil :public t)
77      for method-name = (jmethod-name method)
78      when (not (member method-name implemented-methods :test #'string=))
79      do
80      (let* ((void-p (string= (jclass-name (jmethod-return-type method)) "void"))
81             (arglist (when (plusp (length (jmethod-params method))) '(&rest ignore)))
82             (def `(lambda
83                     ,arglist
84                     ,(when arglist '(declare (ignore ignore)))
85                     ,(if void-p '(values) java:+null+))))
86        (warn "Implementing dummy method ~a for interface ~a"
87              method-name (jclass-name interface))
88        (push (coerce def 'function) method-names-and-defs)
89        (push method-name method-names-and-defs)))
90    (apply #'%jnew-proxy interface method-names-and-defs)))
91
92(defun jmake-invocation-handler (function)
93  (%jmake-invocation-handler function))
94
95(when (autoloadp 'jmake-proxy)
96  (fmakunbound 'jmake-proxy))
97
98(defgeneric jmake-proxy (interface implementation &optional lisp-this)
99  (:documentation "Returns a proxy Java object implementing the provided interface(s) using methods implemented in Lisp - typically closures, but implementations are free to provide other mechanisms. You can pass an optional 'lisp-this' object that will be passed to the implementing methods as their first argument. If you don't provide this object, NIL will be used. The second argument of the Lisp methods is the name of the Java method being implemented. This has the implication that overloaded methods are merged, so you have to manually discriminate them if you want to. The remaining arguments are java-objects wrapping the method's parameters."))
100
101(defun canonicalize-jproxy-interfaces (ifaces)
102  (if (listp ifaces)
103      (mapcar #'jclass ifaces)
104      (list (jclass ifaces))))
105
106
107(defmethod jmake-proxy (interface invocation-handler &optional lisp-this)
108  "Basic implementation that directly uses an invocation handler."
109  (%jmake-proxy (canonicalize-jproxy-interfaces interface) invocation-handler lisp-this))
110
111(defmethod jmake-proxy (interface (implementation function) &optional lisp-this)
112  "Implements a Java interface forwarding method calls to a Lisp function."
113  (%jmake-proxy (canonicalize-jproxy-interfaces interface) (jmake-invocation-handler implementation) lisp-this))
114
115(defmethod jmake-proxy (interface (implementation package) &optional lisp-this)
116  "Implements a Java interface mapping Java method names to symbols in a given package. javaMethodName is mapped to a JAVA-METHOD-NAME symbol. An error is signaled if no such symbol exists in the package, or if the symbol exists but does not name a function."
117  (flet ((java->lisp (name)
118     (with-output-to-string (str)
119       (let ((last-lower-p nil))
120         (map nil (lambda (char)
121        (let ((upper-p (char= (char-upcase char) char)))
122          (when (and last-lower-p upper-p)
123            (princ "-" str))
124          (setf last-lower-p (not upper-p))
125          (princ (char-upcase char) str)))
126        name)))))
127    (%jmake-proxy (canonicalize-jproxy-interfaces interface)
128      (jmake-invocation-handler 
129       (lambda (obj method &rest args)
130         (let ((sym (find-symbol
131         (java->lisp method)
132         implementation)))
133           (unless sym
134       (error "Symbol ~A, implementation of method ~A, not found in ~A"
135          (java->lisp method)
136          method
137          implementation))
138       (if (fboundp sym)
139           (apply (symbol-function sym) obj method args)
140           (error "Function ~A, implementation of method ~A, not found in ~A"
141            sym method implementation)))))
142      lisp-this)))
143
144(defmethod jmake-proxy (interface (implementation hash-table) &optional lisp-this)
145  "Implements a Java interface using closures in an hash-table keyed by Java method name."
146  (%jmake-proxy (canonicalize-jproxy-interfaces interface)
147    (jmake-invocation-handler 
148     (lambda (obj method &rest args)
149       (let ((fn (gethash method implementation)))
150         (if fn
151       (apply fn obj args)
152       (error "Implementation for method ~A not found in ~A"
153        method implementation)))))
154    lisp-this))
155
156(defun jequal (obj1 obj2)
157  "Compares obj1 with obj2 using java.lang.Object.equals()"
158  (jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
159   obj1 obj2))
160
161(defun jobject-class (obj)
162  "Returns the Java class that OBJ belongs to"
163  (jcall (jmethod "java.lang.Object" "getClass") obj))
164
165(defun jclass-superclass (class)
166  "Returns the superclass of CLASS, or NIL if it hasn't got one"
167  (jcall (jmethod "java.lang.Class" "getSuperclass") (jclass class)))
168
169(defun jclass-interfaces (class)
170  "Returns the vector of interfaces of CLASS"
171  (jcall (jmethod "java.lang.Class" "getInterfaces") (jclass class)))
172
173(defun jclass-interface-p (class)
174  "Returns T if CLASS is an interface"
175  (jcall (jmethod "java.lang.Class" "isInterface") (jclass class)))
176
177(defun jclass-superclass-p (class-1 class-2)
178  "Returns T if CLASS-1 is a superclass or interface of CLASS-2"
179  (jcall (jmethod "java.lang.Class" "isAssignableFrom" "java.lang.Class")
180         (jclass class-1)
181         (jclass class-2)))
182
183(defun jclass-array-p (class)
184  "Returns T if CLASS is an array class"
185  (jcall (jmethod "java.lang.Class" "isArray") (jclass class)))
186
187(defun jarray-component-type (atype)
188  "Returns the component type of the array type ATYPE"
189  (assert (jclass-array-p atype))
190  (jcall (jmethod "java.lang.Class" "getComponentType") atype))
191
192(defun jarray-length (java-array)
193  (jstatic "getLength" "java.lang.reflect.Array" java-array)  )
194
195(defun (setf jarray-ref) (new-value java-array &rest indices)
196  (apply #'jarray-set java-array new-value indices))
197
198(defun jnew-array-from-array (element-type array)
199  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
200   initialized from ARRAY"
201  (flet
202    ((row-major-to-index (dimensions n)
203                         (loop for dims on dimensions
204                           with indices
205                           do
206                           (multiple-value-bind (m r) (floor n (apply #'* (cdr dims)))
207                             (push m indices)
208                             (setq n r))
209                           finally (return (nreverse indices)))))
210    (let* ((fill-pointer (when (array-has-fill-pointer-p array) (fill-pointer array)))
211           (dimensions (if fill-pointer (list fill-pointer) (array-dimensions array)))
212           (jarray (apply #'jnew-array element-type dimensions)))
213      (dotimes (i (if fill-pointer fill-pointer (array-total-size array)) jarray)
214        #+maybe_one_day
215        (setf (apply #'jarray-ref jarray (row-major-to-index dimensions i)) (row-major-aref array i))
216        (apply #'(setf jarray-ref) (row-major-aref array i) jarray (row-major-to-index dimensions i))))))
217
218(defun jnew-array-from-list (element-type list)
219  (let ((jarray (jnew-array element-type (length list)))
220  (i 0))
221    (dolist (x list)
222      (setf (jarray-ref jarray i) x
223      i (1+ i)))
224    jarray))
225
226(defun list-from-jarray (jarray)
227  "Returns a list with the elements of `jarray`."
228  (loop for i from 0 below (jarray-length jarray)
229        collect (jarray-ref jarray i)))
230
231(defun vector-from-jarray (jarray)
232  "Returns a vector with the elements of `jarray`."
233  (loop with vec = (make-array (jarray-length jarray))
234        for i from 0 below (jarray-length jarray)
235        do (setf (aref vec i) (jarray-ref jarray i))
236        finally (return vec)))
237
238(defun list-from-jenumeration (jenumeration)
239  "Returns a list with the elements returned by successive `nextElement`
240calls on the java.util.Enumeration `jenumeration`."
241  (loop while (jcall jenumeration
242                     (jmethod "java.util.Enumeration" "hasMoreElements"))
243        collect (jcall jenumeration
244                       (jmethod "java.util.Enumeration" "nextElement"))))
245
246(defun jclass-constructors (class)
247  "Returns a vector of constructors for CLASS"
248  (jcall (jmethod "java.lang.Class" "getConstructors") (jclass class)))
249
250(defun jconstructor-params (constructor)
251  "Returns a vector of parameter types (Java classes) for CONSTRUCTOR"
252  (jcall (jmethod "java.lang.reflect.Constructor" "getParameterTypes") constructor))
253
254(defun jclass-fields (class &key declared public)
255  "Returns a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) fields of CLASS"
256  (let* ((getter (if declared "getDeclaredFields" "getFields"))
257         (fields (jcall (jmethod "java.lang.Class" getter) (jclass class))))
258    (if public (delete-if-not #'jmember-public-p fields) fields)))
259
260(defun jclass-field (class field-name)
261  "Returns the field named FIELD-NAME of CLASS"
262  (jcall (jmethod "java.lang.Class" "getField" "java.lang.String")
263         (jclass class) field-name))
264
265(defun jfield-type (field)
266  "Returns the type (Java class) of FIELD"
267  (jcall (jmethod "java.lang.reflect.Field" "getType") field))
268
269(defun jfield-name (field)
270  "Returns the name of FIELD as a Lisp string"
271  (jcall (jmethod "java.lang.reflect.Field" "getName") field))
272
273
274(defun (setf jfield) (newvalue class-ref-or-field field-or-instance
275          &optional (instance nil instance-supplied-p) unused-value)
276  (declare (ignore unused-value))
277  (if instance-supplied-p
278      (jfield class-ref-or-field field-or-instance instance newvalue)
279      (jfield class-ref-or-field field-or-instance newvalue)))
280
281(defun jclass-methods (class &key declared public)
282  "Return a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) methods of CLASS"
283  (let* ((getter (if declared "getDeclaredMethods" "getMethods"))
284         (methods (jcall (jmethod "java.lang.Class" getter) (jclass class))))
285    (if public (delete-if-not #'jmember-public-p methods) methods)))
286
287(defun jmethod-params (method)
288  "Returns a vector of parameter types (Java classes) for METHOD"
289  (jcall (jmethod "java.lang.reflect.Method" "getParameterTypes") method))
290
291(defun jmethod-return-type (method)
292  "Returns the result type (Java class) of the METHOD"
293  (jcall (jmethod "java.lang.reflect.Method" "getReturnType") method))
294
295(defun jmethod-declaring-class (method)
296  "Returns the Java class declaring METHOD"
297  (jcall (jmethod "java.lang.reflect.Method" "getDeclaringClass") method))
298
299(defun jmethod-name (method)
300  "Returns the name of METHOD as a Lisp string"
301  (jcall (jmethod "java.lang.reflect.Method" "getName") method))
302
303(defun jinstance-of-p (obj class)
304  "OBJ is an instance of CLASS (or one of its subclasses)"
305  (and (java-object-p obj)
306       (jcall (jmethod "java.lang.Class" "isInstance" "java.lang.Object") (jclass class) obj)))
307
308(defun jmember-static-p (member)
309  "MEMBER is a static member of its declaring class"
310  (jstatic (jmethod "java.lang.reflect.Modifier" "isStatic" "int")
311           "java.lang.reflect.Modifier"
312           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
313
314(defun jmember-public-p (member)
315  "MEMBER is a public member of its declaring class"
316  (jstatic (jmethod "java.lang.reflect.Modifier" "isPublic" "int")
317           "java.lang.reflect.Modifier"
318           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
319
320(defun jmember-protected-p (member)
321  "MEMBER is a protected member of its declaring class"
322  (jstatic (jmethod "java.lang.reflect.Modifier" "isProtected" "int")
323           "java.lang.reflect.Modifier"
324           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
325
326(defmethod make-load-form ((object java-object) &optional environment)
327  (declare (ignore environment))
328  (let ((class-name (jclass-name (jclass-of object))))
329    (cond
330     ((string= class-name "java.lang.reflect.Constructor")
331      `(java:jconstructor ,(jclass-name
332                            (jcall (jmethod "java.lang.reflect.Constructor"
333                                            "getDeclaringClass") object))
334                          ,@(loop for arg-type across
335                              (jcall
336                               (jmethod "java.lang.reflect.Constructor"
337                                        "getParameterTypes")
338                               object)
339                              collecting
340                              (jclass-name arg-type))))
341     ((string= class-name "java.lang.reflect.Method")
342      `(java:jmethod ,(jclass-name
343                       (jcall (jmethod "java.lang.reflect.Method"
344                                       "getDeclaringClass") object))
345                     ,(jmethod-name object)
346                     ,@(loop for arg-type across
347                         (jcall
348                          (jmethod "java.lang.reflect.Method"
349                                   "getParameterTypes")
350                          object)
351                         collecting
352                         (jclass-name arg-type))))
353     ((jinstance-of-p object "java.lang.Class")
354      `(java:jclass ,(jcall (jmethod "java.lang.Class" "getName") object)))
355     (t
356      (error "Unknown load-form for ~A" class-name)))))
357
358(defun jproperty-value (obj prop)
359  (%jget-property-value obj prop))
360
361(defun (setf jproperty-value) (value obj prop)
362  (%jset-property-value obj prop value))
363
364;;; higher-level operators
365
366(defmacro chain (target op &rest ops)
367  "Performs chained method invocations. `target' is the receiver object (when the first call is a virtual method call) or a list in the form (:static <jclass>) when the first method call is a static method call. `op' and each of the `ops' are either method designators or lists in the form (<method designator> &rest args), where a method designator is either a string naming a method, or a jmethod object. `chain' will perform the method call specified by `op' on `target'; then, for each of the `ops', `chain' will perform the specified method call using the object returned by the previous method call as the receiver, and will ultimately return the result of the last method call.
368  For example, the form:
369
370  (chain (:static \"java.lang.Runtime\") \"getRuntime\" (\"exec\" \"ls\"))
371
372  is equivalent to the following Java code:
373
374  java.lang.Runtime.getRuntime().exec(\"ls\");"
375  (labels ((canonicalize-op (op) (if (listp op) op (list op)))
376     (compose-arglist (target op) `(,(car op) ,target ,@(cdr op)))
377     (make-binding-for (form) `(,(gensym) ,form))
378     (make-binding (bindings next-op &aux (target (caar bindings)))
379       (cons (make-binding-for
380        `(jcall ,@(compose-arglist target
381                 (canonicalize-op next-op))))
382       bindings)))
383    (let* ((first (if (and (consp target) (eq (first target) :static))
384          `(jstatic ,@(compose-arglist (cadr target) (canonicalize-op op)))
385          `(jcall ,@(compose-arglist target (canonicalize-op op)))))
386     (bindings (nreverse
387          (reduce #'make-binding ops
388            :initial-value (list (make-binding-for first))))))
389      `(let* ,bindings
390   (declare (ignore ,@(mapcar #'car bindings)))))))
391
392(defmacro jmethod-let (bindings &body body)
393  (let ((args (gensym)))
394    `(let ,(mapcar (lambda (binding)
395         `(,(car binding) (jmethod ,@(cdr binding))))
396       bindings)
397       (macrolet ,(mapcar (lambda (binding)
398          `(,(car binding) (&rest ,args)
399             `(jcall ,,(car binding) ,@,args)))
400        bindings)
401   ,@body))))
402
403;;; print-object
404
405(defmethod print-object ((obj java:java-object) stream)
406  (write-string (sys::%write-to-string obj) stream))
407
408(defmethod print-object ((e java:java-exception) stream)
409  (if *print-escape*
410      (print-unreadable-object (e stream :type t :identity t)
411        (format stream "~A"
412                (java:jcall (java:jmethod "java.lang.Object" "toString")
413                            (java:java-exception-cause e))))
414      (format stream "Java exception '~A'."
415              (java:jcall (java:jmethod "java.lang.Object" "toString")
416                          (java:java-exception-cause e)))))
417
418;;; JAVA-CLASS support
419(defconstant +java-lang-object+ (jclass "java.lang.Object"))
420
421(defclass java-class (standard-class)
422  ((jclass :initarg :java-class
423     :initform (error "class is required")
424     :reader java-class-jclass)))
425
426;;init java.lang.Object class
427(defconstant +java-lang-object-class+
428  (%register-java-class +java-lang-object+
429      (mop::ensure-class (make-symbol "java.lang.Object")
430             :metaclass (find-class 'java-class)
431             :direct-superclasses (list (find-class 'java-object))
432             :java-class +java-lang-object+)))
433
434(defun jclass-additional-superclasses (jclass)
435  "Extension point to put additional CLOS classes on the CPL of a CLOS Java class."
436  (let ((supers nil))
437    (when (jclass-interface-p jclass)
438      (push (find-class 'java-object) supers))
439    supers))
440
441(defun ensure-java-class (jclass)
442  (let ((class (%find-java-class jclass)))
443    (if class
444  class
445  (%register-java-class
446   jclass (mop::ensure-class
447     (make-symbol (jclass-name jclass))
448     :metaclass (find-class 'java-class)
449     :direct-superclasses
450     (let ((supers
451      (mapcar #'ensure-java-class
452        (delete nil
453          (concatenate 'list
454                 (list (jclass-superclass jclass))
455                 (jclass-interfaces jclass))))))
456       (append supers (jclass-additional-superclasses jclass)))
457     :java-class jclass)))))
458
459(defmethod mop::compute-class-precedence-list ((class java-class))
460  "Sort classes this way:
461   1. Java classes (but not java.lang.Object)
462   2. Java interfaces
463   3. java.lang.Object
464   4. other classes
465   Rationale:
466   1. Concrete classes are the most specific.
467   2. Then come interfaces.
468     So if a generic function is specialized both on an interface and a concrete class,
469     the concrete class comes first.
470   3. because everything is an Object.
471   4. to handle base CLOS classes.
472   Note: Java interfaces are not sorted among themselves in any way, so if a
473   gf is specialized on two different interfaces and you apply it to an object that
474   implements both, it is unspecified which method will be called."
475  (let ((cpl (nreverse (mop::collect-superclasses* class))))
476    (flet ((score (class)
477       (if (not (typep class 'java-class))
478     4
479     (cond
480       ((jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
481         (java-class-jclass class) +java-lang-object+) 3)
482       ((jclass-interface-p (java-class-jclass class)) 2)
483       (t 1)))))
484      (stable-sort cpl #'(lambda (x y)
485         (< (score x) (score y)))))))
486   
487(defmethod make-instance ((class java-class) &rest initargs &key &allow-other-keys)
488  (declare (ignore initargs))
489  (error "make-instance not supported for ~S" class))
490
491(provide "JAVA")
Note: See TracBrowser for help on using the repository browser.