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

Last change on this file since 12774 was 12774, checked in by astalla, 13 years ago

Added support for implementing multiple interfaces using jmake-proxy

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 17.7 KB
Line 
1;;; java.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves, Andras Simon
4;;; $Id: java.lisp 12774 2010-07-01 21:02:45Z astalla $
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        (null (make-immediate-object nil :ref)))
71    (loop for method across
72      (jclass-methods interface :declared nil :public t)
73      for method-name = (jmethod-name method)
74      when (not (member method-name implemented-methods :test #'string=))
75      do
76      (let* ((void-p (string= (jclass-name (jmethod-return-type method)) "void"))
77             (arglist (when (plusp (length (jmethod-params method))) '(&rest ignore)))
78             (def `(lambda
79                     ,arglist
80                     ,(when arglist '(declare (ignore ignore)))
81                     ,(if void-p '(values) null))))
82        (warn "Implementing dummy method ~a for interface ~a"
83              method-name (jclass-name interface))
84        (push (coerce def 'function) method-names-and-defs)
85        (push method-name method-names-and-defs)))
86    (apply #'%jnew-proxy interface method-names-and-defs)))
87
88(defun jmake-invocation-handler (function)
89  (%jmake-invocation-handler function))
90
91(when (autoloadp 'jmake-proxy)
92  (fmakunbound 'jmake-proxy))
93
94(defgeneric jmake-proxy (interface implementation &optional lisp-this)
95  (: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."))
96
97(defun canonicalize-jproxy-interfaces (ifaces)
98  (if (listp ifaces)
99      (mapcar #'jclass ifaces)
100      (list (jclass ifaces))))
101
102
103(defmethod jmake-proxy (interface invocation-handler &optional lisp-this)
104  "Basic implementation that directly uses an invocation handler."
105  (%jmake-proxy (canonicalize-jproxy-interfaces interface) invocation-handler lisp-this))
106
107(defmethod jmake-proxy (interface (implementation function) &optional lisp-this)
108  "Implements a Java interface forwarding method calls to a Lisp function."
109  (%jmake-proxy (canonicalize-jproxy-interfaces interface) (jmake-invocation-handler implementation) lisp-this))
110
111(defmethod jmake-proxy (interface (implementation package) &optional lisp-this)
112  "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."
113  (flet ((java->lisp (name)
114     (with-output-to-string (str)
115       (let ((last-lower-p nil))
116         (map nil (lambda (char)
117        (let ((upper-p (char= (char-upcase char) char)))
118          (when (and last-lower-p upper-p)
119            (princ "-" str))
120          (setf last-lower-p (not upper-p))
121          (princ (char-upcase char) str)))
122        name)))))
123    (%jmake-proxy (canonicalize-jproxy-interfaces interface)
124      (jmake-invocation-handler 
125       (lambda (obj method &rest args)
126         (let ((sym (find-symbol
127         (java->lisp method)
128         implementation)))
129           (unless sym
130       (error "Symbol ~A, implementation of method ~A, not found in ~A"
131          (java->lisp method)
132          method
133          implementation))
134       (if (fboundp sym)
135           (apply (symbol-function sym) obj method args)
136           (error "Function ~A, implementation of method ~A, not found in ~A"
137            sym method implementation)))))
138      lisp-this)))
139
140(defmethod jmake-proxy (interface (implementation hash-table) &optional lisp-this)
141  "Implements a Java interface using closures in an hash-table keyed by Java method name."
142  (%jmake-proxy (canonicalize-jproxy-interfaces interface)
143    (jmake-invocation-handler 
144     (lambda (obj method &rest args)
145       (let ((fn (gethash method implementation)))
146         (if fn
147       (apply fn obj args)
148       (error "Implementation for method ~A not found in ~A"
149        method implementation)))))
150    lisp-this))
151
152(defun jobject-class (obj)
153  "Returns the Java class that OBJ belongs to"
154  (jcall (jmethod "java.lang.Object" "getClass") obj))
155
156(defun jclass-superclass (class)
157  "Returns the superclass of CLASS, or NIL if it hasn't got one"
158  (jcall (jmethod "java.lang.Class" "getSuperclass") (jclass class)))
159
160(defun jclass-interfaces (class)
161  "Returns the vector of interfaces of CLASS"
162  (jcall (jmethod "java.lang.Class" "getInterfaces") (jclass class)))
163
164(defun jclass-interface-p (class)
165  "Returns T if CLASS is an interface"
166  (jcall (jmethod "java.lang.Class" "isInterface") (jclass class)))
167
168(defun jclass-superclass-p (class-1 class-2)
169  "Returns T if CLASS-1 is a superclass or interface of CLASS-2"
170  (jcall (jmethod "java.lang.Class" "isAssignableFrom" "java.lang.Class")
171         (jclass class-1)
172         (jclass class-2)))
173
174(defun jclass-array-p (class)
175  "Returns T if CLASS is an array class"
176  (jcall (jmethod "java.lang.Class" "isArray") (jclass class)))
177
178(defun jarray-component-type (atype)
179  "Returns the component type of the array type ATYPE"
180  (assert (jclass-array-p atype))
181  (jcall (jmethod "java.lang.Class" "getComponentType") atype))
182
183(defun jarray-length (java-array)
184  (jstatic "getLength" "java.lang.reflect.Array" java-array)  )
185
186(defun (setf jarray-ref) (new-value java-array &rest indices)
187  (apply #'jarray-set java-array new-value indices))
188
189(defun jnew-array-from-array (element-type array)
190  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
191   initialized from ARRAY"
192  (flet
193    ((row-major-to-index (dimensions n)
194                         (loop for dims on dimensions
195                           with indices
196                           do
197                           (multiple-value-bind (m r) (floor n (apply #'* (cdr dims)))
198                             (push m indices)
199                             (setq n r))
200                           finally (return (nreverse indices)))))
201    (let* ((fill-pointer (when (array-has-fill-pointer-p array) (fill-pointer array)))
202           (dimensions (if fill-pointer (list fill-pointer) (array-dimensions array)))
203           (jarray (apply #'jnew-array element-type dimensions)))
204      (dotimes (i (if fill-pointer fill-pointer (array-total-size array)) jarray)
205        #+maybe_one_day
206        (setf (apply #'jarray-ref jarray (row-major-to-index dimensions i)) (row-major-aref array i))
207        (apply #'(setf jarray-ref) (row-major-aref array i) jarray (row-major-to-index dimensions i))))))
208
209(defun jnew-array-from-list (element-type list)
210  (let ((jarray (jnew-array element-type (length list)))
211  (i 0))
212    (dolist (x list)
213      (setf (jarray-ref jarray i) x
214      i (1+ i)))
215    jarray))
216
217(defun jclass-constructors (class)
218  "Returns a vector of constructors for CLASS"
219  (jcall (jmethod "java.lang.Class" "getConstructors") (jclass class)))
220
221(defun jconstructor-params (constructor)
222  "Returns a vector of parameter types (Java classes) for CONSTRUCTOR"
223  (jcall (jmethod "java.lang.reflect.Constructor" "getParameterTypes") constructor))
224
225(defun jclass-fields (class &key declared public)
226  "Returns a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) fields of CLASS"
227  (let* ((getter (if declared "getDeclaredFields" "getFields"))
228         (fields (jcall (jmethod "java.lang.Class" getter) (jclass class))))
229    (if public (delete-if-not #'jmember-public-p fields) fields)))
230
231(defun jclass-field (class field-name)
232  "Returns the field named FIELD-NAME of CLASS"
233  (jcall (jmethod "java.lang.Class" "getField" "java.lang.String")
234         (jclass class) field-name))
235
236(defun jfield-type (field)
237  "Returns the type (Java class) of FIELD"
238  (jcall (jmethod "java.lang.reflect.Field" "getType") field))
239
240(defun jfield-name (field)
241  "Returns the name of FIELD as a Lisp string"
242  (jcall (jmethod "java.lang.reflect.Field" "getName") field))
243
244
245(defun (setf jfield) (newvalue class-ref-or-field field-or-instance
246          &optional (instance nil instance-supplied-p) unused-value)
247  (declare (ignore unused-value))
248  (if instance-supplied-p
249      (jfield class-ref-or-field field-or-instance instance newvalue)
250      (jfield class-ref-or-field field-or-instance newvalue)))
251
252(defun jclass-methods (class &key declared public)
253  "Return a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) methods of CLASS"
254  (let* ((getter (if declared "getDeclaredMethods" "getMethods"))
255         (methods (jcall (jmethod "java.lang.Class" getter) (jclass class))))
256    (if public (delete-if-not #'jmember-public-p methods) methods)))
257
258(defun jmethod-params (method)
259  "Returns a vector of parameter types (Java classes) for METHOD"
260  (jcall (jmethod "java.lang.reflect.Method" "getParameterTypes") method))
261
262(defun jmethod-return-type (method)
263  "Returns the result type (Java class) of the METHOD"
264  (jcall (jmethod "java.lang.reflect.Method" "getReturnType") method))
265
266(defun jmethod-declaring-class (method)
267  "Returns the Java class declaring METHOD"
268  (jcall (jmethod "java.lang.reflect.Method" "getDeclaringClass") method))
269
270(defun jmethod-name (method)
271  "Returns the name of METHOD as a Lisp string"
272  (jcall (jmethod "java.lang.reflect.Method" "getName") method))
273
274(defun jinstance-of-p (obj class)
275  "OBJ is an instance of CLASS (or one of its subclasses)"
276  (and (java-object-p obj)
277       (jcall (jmethod "java.lang.Class" "isInstance" "java.lang.Object") (jclass class) obj)))
278
279(defun jmember-static-p (member)
280  "MEMBER is a static member of its declaring class"
281  (jstatic (jmethod "java.lang.reflect.Modifier" "isStatic" "int")
282           "java.lang.reflect.Modifier"
283           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
284
285(defun jmember-public-p (member)
286  "MEMBER is a public member of its declaring class"
287  (jstatic (jmethod "java.lang.reflect.Modifier" "isPublic" "int")
288           "java.lang.reflect.Modifier"
289           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
290
291(defun jmember-protected-p (member)
292  "MEMBER is a protected member of its declaring class"
293  (jstatic (jmethod "java.lang.reflect.Modifier" "isProtected" "int")
294           "java.lang.reflect.Modifier"
295           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
296
297(defmethod make-load-form ((object java-object) &optional environment)
298  (declare (ignore environment))
299  (let ((class-name (jclass-name (jclass-of object))))
300    (cond
301     ((string= class-name "java.lang.reflect.Constructor")
302      `(java:jconstructor ,(jclass-name
303                            (jcall (jmethod "java.lang.reflect.Constructor"
304                                            "getDeclaringClass") object))
305                          ,@(loop for arg-type across
306                              (jcall
307                               (jmethod "java.lang.reflect.Constructor"
308                                        "getParameterTypes")
309                               object)
310                              collecting
311                              (jclass-name arg-type))))
312     ((string= class-name "java.lang.reflect.Method")
313      `(java:jmethod ,(jclass-name
314                       (jcall (jmethod "java.lang.reflect.Method"
315                                       "getDeclaringClass") object))
316                     ,(jmethod-name object)
317                     ,@(loop for arg-type across
318                         (jcall
319                          (jmethod "java.lang.reflect.Method"
320                                   "getParameterTypes")
321                          object)
322                         collecting
323                         (jclass-name arg-type))))
324     ((jinstance-of-p object "java.lang.Class")
325      `(java:jclass ,(jcall (jmethod "java.lang.Class" "getName") object)))
326     (t
327      (error "Unknown load-form for ~A" class-name)))))
328
329(defun jproperty-value (obj prop)
330  (%jget-property-value obj prop))
331
332(defun (setf jproperty-value) (value obj prop)
333  (%jset-property-value obj prop value))
334
335;;; print-object
336
337(defmethod print-object ((obj java:java-object) stream)
338  (write-string (sys::%write-to-string obj) stream))
339
340(defmethod print-object ((e java:java-exception) stream)
341  (if *print-escape*
342      (print-unreadable-object (e stream :type t :identity t)
343        (format stream "~A"
344                (java:jcall (java:jmethod "java.lang.Object" "toString")
345                            (java:java-exception-cause e))))
346      (format stream "Java exception '~A'."
347              (java:jcall (java:jmethod "java.lang.Object" "toString")
348                          (java:java-exception-cause e)))))
349
350;;; JAVA-CLASS support
351(defconstant +java-lang-object+ (jclass "java.lang.Object"))
352
353(defclass java-class (standard-class)
354  ((jclass :initarg :java-class
355     :initform (error "class is required")
356     :reader java-class-jclass)))
357
358;;init java.lang.Object class
359(defconstant +java-lang-object-class+
360  (%register-java-class +java-lang-object+
361      (mop::ensure-class (make-symbol "java.lang.Object")
362             :metaclass (find-class 'java-class)
363             :direct-superclasses (list (find-class 'java-object))
364             :java-class +java-lang-object+)))
365
366(defun ensure-java-class (jclass)
367  (let ((class (%find-java-class jclass)))
368    (if class
369  class
370  (%register-java-class
371   jclass (mop::ensure-class
372     (make-symbol (jclass-name jclass))
373     :metaclass (find-class 'java-class)
374     :direct-superclasses
375     (let ((supers
376      (mapcar #'ensure-java-class
377        (delete nil
378          (concatenate 'list
379                 (list (jclass-superclass jclass))
380                 (jclass-interfaces jclass))))))
381       (if (jclass-interface-p jclass)
382           (append supers (list (find-class 'java-object)))
383           supers))
384     :java-class jclass)))))
385
386(defmethod mop::compute-class-precedence-list ((class java-class))
387  "Sort classes this way:
388   1. Java classes (but not java.lang.Object)
389   2. Java interfaces
390   3. java.lang.Object
391   4. other classes
392   Rationale:
393   1. Concrete classes are the most specific.
394   2. Then come interfaces.
395     So if a generic function is specialized both on an interface and a concrete class,
396     the concrete class comes first.
397   3. because everything is an Object.
398   4. to handle base CLOS classes.
399   Note: Java interfaces are not sorted among themselves in any way, so if a
400   gf is specialized on two different interfaces and you apply it to an object that
401   implements both, it is unspecified which method will be called."
402  (let ((cpl (nreverse (mop::collect-superclasses* class))))
403    (flet ((score (class)
404       (if (not (typep class 'java-class))
405     4
406     (cond
407       ((jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
408         (java-class-jclass class) +java-lang-object+) 3)
409       ((jclass-interface-p (java-class-jclass class)) 2)
410       (t 1)))))
411      (stable-sort cpl #'(lambda (x y)
412         (< (score x) (score y)))))))
413   
414(defmethod make-instance ((class java-class) &rest initargs &key &allow-other-keys)
415  (declare (ignore initargs))
416  (error "make-instance not supported for ~S" class))
417
418(provide "JAVA")
Note: See TracBrowser for help on using the repository browser.