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

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

Remove deprecated use of JAVA:MAKE-IMMEDIATE-OBJECT.

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