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

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

Support for custom defclass options for user-defined metaclasses.
Introduced variable java:*classloader* which holds the classloader used by jclass and friends,
and primitives to create new classloaders and (untested) add new URLs to the classloader at runtime.

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