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

Last change on this file since 13967 was 13967, checked in by Mark Evenson, 9 years ago

JAVA:JINPUT-STREAM returns the underlying java.io.InputStream? for any PATHNAME resolved by CL:TRUENAME.

SYS:ENSURE-INPUT-STREAM is the primitive wrapping the execution of Pathname.getInputStream().

My name is <evenson.not.org@…>, and I support this API.

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