source: trunk/abcl/contrib/jss/invoke.lisp

Last change on this file was 15105, checked in by Evenson Not Org, 18 months ago

Make use of warning muffling
(Olof-Joachim Frahm)

Merges <https://github.com/armedbear/abcl/pull/68>.

From <https://github.com/armedbear/abcl/pull/68/commits/c6e2dde2d824b3a74fc4a1d297c522cb38101d3f>.

File size: 28.2 KB
Line 
1;; Copyright (C) 2005 Alan Ruttenberg
2;; Copyright (C) 2011-2 Mark Evenson
3;;
4;; Since JSS 1.0 was largely derivative of the Jscheme System, the
5;; current system is licensed under the same terms, namely:
6
7;; This software is provided 'as-is', without any express or
8;; implied warranty.
9
10;; In no event will the author be held liable for any damages
11;; arising from the use of this software.
12
13;; Permission is granted to anyone to use this software for any
14;; purpose, including commercial applications, and to alter it
15;; and redistribute it freely, subject to the following
16;; restrictions:
17
18;; 1. The origin of this software must not be misrepresented; you
19;;    must not claim that you wrote the original software. If you
20;;    use this software in a product, an acknowledgment in the
21;;    product documentation would be appreciated but is not
22;;    required.
23
24;; 2. Altered source versions must be plainly marked as such, and
25;;    must not be misrepresented as being the original software.
26
27;; 3. This notice may not be removed or altered from any source
28;;    distribution.
29
30
31;; The dynamic dispatch of the java.lang.reflect package is used to
32;; make it real easy, if perhaps less efficient, to write Java code
33;; since you don't need to be bothered with imports, or with figuring
34;; out which method to call.  The only time that you need to know a
35;; class name is when you want to call a static method, or a
36;; constructor, and in those cases, you only need to know enough of
37;; the class name that is unique wrt to the classes on your classpath.
38;;
39;; Java methods look like this: #"toString". Java classes are
40;; represented as symbols, which are resolved to the appropriate java
41;; class name. When ambiguous, you need to be more specific. A simple example:
42
43;; (let ((sw (new 'StringWriter)))
44;;   (#"write" sw "Hello ")
45;;   (#"write" sw "World")
46;;   (print (#"toString" sw)))
47
48;; What's happened here? First, all the classes in all the jars in the
49;; classpath have been collected.  For each class a.b.C.d, we have
50;; recorded that b.c.d, b.C.d, C.d, c.d, and d potentially refer to
51;; this class. In your call to new, as long as the symbol can refer to
52;; only one class, we use that class. In this case, it is
53;; java.io.StringWriter. You could also have written (new
54;; 'io.stringwriter), (new '|io.StringWriter|), (new
55;; 'java.io.StringWriter)...
56
57;; the call (#"write" sw "Hello "), uses the code in invoke.java to
58;; call the method named "write" with the arguments sw and "Hello ".
59;; JSS figures out the right java method to call, and calls it.
60
61;; If you want to do a raw java call, use #0"toString". Raw calls
62;; return their results as Java objects, avoiding doing the usual Java
63;; object to Lisp object conversions that ABCL does.
64
65;; (with-constant-signature ((name jname raw?)*) &body body)
66;; binds a macro which expands to a jcall, promising that the same method
67;; will be called every time. Use this if you are making a lot of calls and
68;; want to avoid the overhead of a the dynamic dispatch.
69;; e.g. (with-constant-signature ((tostring "toString"))
70;;        (time (dotimes (i 10000) (tostring "foo"))))
71;; runs about 3x faster than (time (dotimes (i 10000) (#"toString" "foo")))
72;;
73;; (with-constant-signature ((tostring "toString" t)) ...) will cause the
74;; toString to be a raw java call. see get-all-jar-classnames below for an example.
75;;
76;; Implementation is that the first time the function is called, the
77;; method is looked up based on the arguments passed, and thereafter
78;; that method is called directly.  Doesn't work for static methods at
79;; the moment (lazy)
80;;
81;; (japropos string) finds all class names matching string
82;; (jcmn class-name) lists the names of all methods for the class
83;;
84;; TODO
85;;   - Make with-constant-signature work for static methods too.
86;;   - #2"toString" to work like function scoped (with-constant-signature ((tostring "toString")) ...)
87;;   - #3"toString" to work like runtime scoped (with-constant-signature ((tostring "toString")) ...)
88;;      (both probably need compiler support to work)
89;;   - Maybe get rid of second " in reader macro. #"toString looks nicer, but might
90;;     confuse lisp mode.
91;;   - write jmap, analogous to map, but can take java collections, java arrays etc.
92;;      In progress with jss-3.5.0's JSS:MAP
93;;   - write loop clauses for java collections.
94;;   - Register classes in .class files below classpath directories (when :wild-inferiors works)
95;;   - Make documentation like Edi Weitz
96;;
97;; Thanks: Peter Graves, Jscheme developers, Mike Travers for skij, 
98;; Andras Simon for jfli-abcl which bootstrapped me and taught me how to do
99;; get-all-jar-classnames
100;;
101
102;; changelog
103
104;; Sat January 28, 2006, alanr:
105
106;; Change imports strategy. Only index by last part of class name,
107;; case insensitive. Make the lookup-class-name logic be a bit more
108;; complicated. This substantially reduces the time it takes to do the
109;; auto imports and since class name lookup is relatively infrequent,
110;; and in any case cached, this doesn't effect run time speed.  (did
111;; try caching, but didn't pay - more time was spent reading and
112;; populating large hash table)
113;;
114;; Split class path by ";" in addition to ":" for windows.
115;;
116;; Tested on windows, linux.
117
118;; 2011-05-21 Mark Evenson
119;;   "ported" to native ABCL without needing the jscheme.jar or bsh-2.0b4.jar
120
121(in-package :jss)
122
123(eval-when (:compile-toplevel :load-toplevel :execute)
124  (defvar *do-auto-imports* t 
125    "Whether to automatically introspect all Java classes on the classpath when JSS is loaded."))
126
127(defvar *muffle-warnings* t)
128
129(defvar *imports-resolved-classes* (make-hash-table :test 'equalp))
130
131(defun find-java-class (name)
132  "Returns the java.lang.Class representation of NAME.
133
134NAME can either string or a symbol according to the usual JSS conventions."
135  (jclass (maybe-resolve-class-against-imports name)))
136
137(defmacro invoke-add-imports (&rest imports)
138  "Push these imports onto the search path. If multiple, earlier in list take precedence"
139  `(eval-when (:compile-toplevel :load-toplevel :execute)
140     (clrhash *imports-resolved-classes*)
141     (dolist (i (reverse ',imports))
142       (setq *imports-resolved-classes* (delete i *imports-resolved-classes* :test 'equal))
143       )))
144
145(defun clear-invoke-imports ()
146  (clrhash *imports-resolved-classes*))
147
148(defun maybe-resolve-class-against-imports (classname)
149  (or (gethash (string classname) *imports-resolved-classes*)
150      (let ((found (lookup-class-name classname)))
151        (if found
152            (progn 
153              (setf (gethash classname *imports-resolved-classes*) found)
154              found)
155            (string classname)))))
156
157(defvar *class-name-to-full-case-insensitive* (make-hash-table :test 'equalp))
158
159;; This is the function that calls invoke to call your java
160;; method. The first argument is the method name or 'new. The second
161;; is the object you are calling it on, followed by the rest of the
162;; arguments. If the "object" is a symbol, then that symbol is assumed
163;; to be a java class, and a static method on the class is called,
164;; otherwise a regular method is called.
165
166(defun invoke (method object &rest args)
167  (invoke-restargs method object args))
168
169(defun invoke-restargs (method object args &optional (raw? nil))
170  (let* ((object-as-class-name 
171          (if (symbolp object) (maybe-resolve-class-against-imports object)))
172         (object-as-class 
173          (if object-as-class-name (find-java-class object-as-class-name))))
174    (if (eq method 'new)
175        (apply #'jnew (or object-as-class-name object) args)
176        (if raw?
177            (if (symbolp object)
178                (apply #'jstatic-raw method object-as-class  args)
179                (apply #'jcall-raw method object  args))
180            (if (symbolp object)
181                (apply #'jstatic method object-as-class args)
182                (apply #'jcall method object args))))))
183
184(defconstant +set-accessible+ 
185  (jmethod "java.lang.reflect.AccessibleObject" "setAccessible" "boolean"))
186
187(defun invoke-find-method (method object args)
188  (let ((result 
189         (if (symbolp object)
190                ;;; static method
191             (apply #'jmethod (lookup-class-name object) 
192                    method (mapcar #'jobject-class args))
193                  ;;; instance method
194             (apply #'jresolve-method 
195                    method object args))))
196    (jcall +set-accessible+ result +true+)
197    result))
198
199;; This is the reader macro for java methods. it translates the method
200;; into a lambda form that calls invoke. Which is nice because you
201;; can, e.g. do this: (mapcar #"toString" list-of-java-objects). The reader
202;; macro takes one arg. If 0, then jstatic-raw is called, so that abcl doesn't
203;; automagically convert the returned java object into a lisp object. So
204;; #0"toString" returns a java.lang.String object, where as #"toString" returns
205;; a regular Lisp string as ABCL converts the Java string to a Lisp string.
206
207(eval-when (:compile-toplevel :load-toplevel :execute)
208  (defun read-invoke (stream char arg) 
209    (unread-char char stream)
210    (let ((name (read stream)))
211      (if (or (find #\. name) (find #\{ name))
212          (jss-transform-to-field name arg)
213          (let ((object-var (gensym))
214                (args-var (gensym)))
215            `(lambda (,object-var &rest ,args-var) 
216               (invoke-restargs ,name  ,object-var ,args-var ,(eql arg 0)))))))
217  (set-dispatch-macro-character #\# #\" 'read-invoke))
218
219(defmacro with-constant-signature (fname-jname-pairs &body body)
220  "Expand all references to FNAME-JNAME-PAIRS in BODY into static function calls promising that the same function bound in the FNAME-JNAME-PAIRS will be invoked with the same argument signature.
221
222FNAME-JNAME-PAIRS is a list of (symbol function &optional raw)
223elements where symbol will be the symbol bound to the method named by
224the string function.  If the optional parameter raw is non-nil, the
225result will be the raw JVM object, uncoerced by the usual conventions.
226
227Use this macro if you are making a lot of calls and
228want to avoid the overhead of the dynamic dispatch."
229
230  (if (null fname-jname-pairs)
231      `(progn ,@body)
232      (destructuring-bind ((fname jname &optional raw) &rest ignore) fname-jname-pairs
233        (declare (ignore ignore))
234        (let ((varname (gensym)))
235          `(let ((,varname nil))
236             (macrolet ((,fname (&rest args)
237                          `(if ,',varname
238                               (if ,',raw
239                                   (jcall-raw ,',varname ,@args)
240                                   (jcall ,',varname ,@args))
241                               (progn
242                                 (setq ,',varname (invoke-find-method ,',jname ,(car args) (list ,@(rest args))))
243                                 (if ,',raw
244                                     (jcall-raw ,',varname ,@args)
245                                     (jcall ,',varname ,@args))))))
246               (with-constant-signature ,(cdr fname-jname-pairs)
247                 ,@body)))))))
248
249(defvar *class-lookup-overrides*)
250
251(defmacro with-class-lookup-disambiguated (overrides &body body)
252  "Suppose you have code that references class using the symbol 'object, and this is ambiguous. E.g. in my system java.lang.Object, org.omg.CORBA.Object. Use (with-class-lookup-disambiguated (lang.object) ...). Within dynamic scope, find-java-class first sees if any of these match, and if so uses them to lookup the class."
253  `(let ((*class-lookup-overrides* ',overrides))
254     ,@body))
255
256(defun maybe-found-in-overridden (name)
257  (when (boundp '*class-lookup-overrides*)
258      (let ((found (find-if (lambda(el) (#"matches" (string el) (concatenate 'string "(?i).*" (string name) "$")))
259          *class-lookup-overrides*)))
260  (if found
261      (let ((*class-lookup-overrides* nil))
262        (lookup-class-name found))))))
263
264
265(defun lookup-class-name (name &key
266                                 (table *class-name-to-full-case-insensitive*)
267                                 (muffle-warning *muffle-warnings*)
268                                 (return-ambiguous nil))
269  (let ((overridden (maybe-found-in-overridden name)))
270    (when overridden (return-from lookup-class-name overridden)))
271  (setq name (string name))
272  (let* (;; cant (last-name-pattern (#"compile" '|java.util.regex.Pattern| ".*?([^.]*)$"))
273         ;; reason: bootstrap - the class name would have to be looked up...
274         (last-name-pattern (load-time-value (jstatic (jmethod "java.util.regex.Pattern" "compile"
275                                                               (jclass "java.lang.String"))
276                                                      (jclass "java.util.regex.Pattern") 
277                                                      ".*?([^.]*)$")))
278         (last-name 
279          (let ((matcher (#0"matcher" last-name-pattern name)))
280            (#"matches" matcher)
281            (#"group" matcher 1))))
282    (let* ((bucket (gethash last-name *class-name-to-full-case-insensitive*))
283           (bucket-length (length bucket)))
284      (or (find name bucket :test 'equalp)
285          (flet ((matches-end (end full test)
286                   (= (+ (or (search end full :from-end t :test test) -10)
287                         (length end))
288                      (length full)))
289                 (ambiguous (choices)
290       (if return-ambiguous 
291           (return-from lookup-class-name choices)
292           (error "Ambiguous class name: ~a can be ~{~a~^, ~}" name choices))))
293            (if (zerop bucket-length)
294    (progn (unless muffle-warning (warn "can't find class named ~a" name)) nil)
295                (let ((matches (loop for el in bucket when (matches-end name el 'char=) collect el)))
296                  (if (= (length matches) 1)
297                      (car matches)
298                      (if (= (length matches) 0)
299                          (let ((matches (loop for el in bucket when (matches-end name el 'char-equal) collect el)))
300                            (if (= (length matches) 1)
301                                (car matches)
302                                (if (= (length matches) 0)
303            (progn (unless muffle-warning (warn "can't find class named ~a" name)) nil)
304                                    (ambiguous matches))))
305                          (ambiguous matches))))))))))
306
307(defun get-all-jar-classnames (jar-file-name)
308  (let* ((jar (jnew (jconstructor "java.util.jar.JarFile" (jclass "java.lang.String")) (namestring (truename jar-file-name))))
309         (entries (#"entries" jar)))
310    (with-constant-signature ((matcher "matcher" t) (substring "substring")
311                              (jreplace "replace" t) (jlength "length")
312                              (matches "matches") (getname "getName" t)
313                              (next "nextElement" t) (hasmore "hasMoreElements")
314                              (group "group"))
315      (loop while (hasmore entries)
316         for name =  (getname (next entries))
317         with class-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*\\.class$")
318         with name-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*?([^.]*)$")
319         when (matches (matcher class-pattern name))
320         collect
321           (let* ((fullname (substring (jreplace name #\/ #\.) 0 (- (jlength name) 6)))
322                  (matcher (matcher name-pattern fullname))
323                  (name (progn (matches matcher) (group matcher 1))))
324             (cons name fullname))
325           ))))
326
327(defun jar-import (file)
328  "Import all the Java classes contained in the pathname FILE into the JSS dynamic lookup cache."
329  (when (probe-file file)
330    (loop for (name . full-class-name) in (get-all-jar-classnames file)
331       do 
332         (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
333                  :test 'equal))))
334
335(defun new (class-name &rest args)
336  "Invoke the Java constructor for CLASS-NAME with ARGS.
337
338CLASS-NAME may either be a symbol or a string according to the usual JSS conventions."
339  (invoke-restargs 'new class-name args))
340
341(defvar *running-in-osgi* (ignore-errors (jclass "org.osgi.framework.BundleActivator")))
342
343(define-condition no-such-java-field (error)
344  ((field-name
345    :initarg :field-name
346    :reader field-name
347    )
348   (object
349    :initarg :object
350    :reader object
351    ))
352  (:report (lambda (c stream)
353             (format stream "Unable to find a FIELD named ~a for ~a"
354                     (field-name c) (object c))))
355  )
356
357(defun get-java-field (object field &optional (try-harder *running-in-osgi*))
358  "Get the value of the FIELD contained in OBJECT.
359If OBJECT is a symbol it names a dot qualified static FIELD."
360  (if try-harder
361      (let* ((class (if (symbolp object)
362                        (setq object (find-java-class object))
363                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)))
364                            object
365                            (jobject-class object))))
366             (jfield (if (java-object-p field)
367                         field
368                         (or (find-declared-field field class)
369                             (error 'no-such-java-field :field-name field :object object)))))
370        (#"setAccessible" jfield +true+)
371        (values (#"get" jfield object) jfield))
372      (if (symbolp object)
373          (let ((class (find-java-class object)))
374            (jfield class field))
375          (jfield field object))))
376
377(defun find-declared-field (field class)
378  "Return a FIELD object corresponding to the definition of FIELD
379\(a string\) visible at CLASS. *Not* restricted to public classes, and checks
380all superclasses of CLASS.
381   Returns NIL if no field object is found."
382  (loop while class
383     for field-obj = (get-declared-field class field)
384     if field-obj
385     do (return-from find-declared-field field-obj)
386     else
387     do (setf class (jclass-superclass class)))
388  nil)
389
390(defun get-declared-field (class fieldname)
391  (find fieldname (#"getDeclaredFields" class)
392        :key 'jfield-name :test 'equal))
393
394;; TODO use #"getSuperclass" and #"getInterfaces" to see whether there
395;; are fields in superclasses that we might set
396(defun set-java-field (object field value &optional (try-harder *running-in-osgi*))
397  "Set the FIELD of OBJECT to VALUE.
398If OBJECT is a symbol, it names a dot qualified Java class to look for
399a static FIELD.  If OBJECT is an instance of java:java-object, the
400associated is used to look up the static FIELD."
401  (if try-harder
402      (let* ((class (if (symbolp object)
403                        (setq object (find-java-class object))
404                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)) )
405                            object
406                            (jobject-class object))))
407             (jfield (if (java-object-p field)
408                         field
409                         (or (find-declared-field field class)
410                             (error 'no-such-java-field :field-name field :object object)))))
411        (#"setAccessible" jfield +true+)
412        (values (#"set" jfield object value) jfield))
413      (if (symbolp object)
414          (let ((class (find-java-class object)))
415            (setf (jfield (#"getName" class) field) value))
416          (if (typep object 'java-object)
417              (setf (jfield (jclass-of object) field) value)
418              (setf (jfield object field) value)))))
419
420(defun (setf get-java-field) (value object field &optional (try-harder *running-in-osgi*))
421  (set-java-field object field value try-harder))
422
423
424(defconstant +for-name+ 
425  (jmethod "java.lang.Class" "forName" "java.lang.String" "boolean" "java.lang.ClassLoader"))
426
427(defun find-java-class (name)
428  (or (jstatic +for-name+ "java.lang.Class" 
429               (maybe-resolve-class-against-imports name) +true+ java::*classloader*)
430      (ignore-errors (jclass (maybe-resolve-class-against-imports name)))))
431
432(defmethod print-object ((obj (jclass "java.lang.Class")) stream) 
433  (print-unreadable-object (obj stream :identity nil)
434    (format stream "java class ~a" (jclass-name obj))))
435
436(defmethod print-object ((obj (jclass "java.lang.reflect.Method")) stream) 
437  (print-unreadable-object (obj stream :identity nil)
438    (format stream "method ~a" (#"toString" obj))))
439
440(defun do-auto-imports ()
441  (labels ((expand-paths (cp)
442             (loop :for s :in cp
443                :appending (loop :for entry 
444                              :in (let ((p (pathname s)))
445                                    (if (wild-pathname-p p)
446                                        (directory p)
447                                        (list p)))
448                              :collecting entry)))
449           (import-classpath (cp)
450             (mapcar 
451              (lambda (p) 
452                (when *load-verbose*
453                  (format t ";; Importing ~A~%" p))
454                (cond 
455                  ((file-directory-p p) )
456                  ((equal (pathname-type p) "jar")
457                   (jar-import (merge-pathnames p
458                                                (format nil "~a/" (jstatic "getProperty" "java.lang.System" "user.dir")))))))
459              cp))
460           (split-classpath (cp)
461             (coerce 
462              (jcall "split" cp 
463                     (string (jfield (jclass "java.io.File") "pathSeparatorChar")))
464              'cons))
465           (do-imports (cp)
466             (import-classpath (expand-paths (split-classpath cp)))))
467    (do-imports (jcall "getClassPath" (jstatic "getRuntimeMXBean" '|java.lang.management.ManagementFactory|)))
468    (do-imports (jcall "getBootClassPath" (jstatic "getRuntimeMXBean" '|java.lang.management.ManagementFactory|)))))
469
470(eval-when (:load-toplevel :execute)
471  (when *do-auto-imports* 
472    (do-auto-imports)))
473
474(defun japropos (string)
475  "Output the names of all Java class names loaded in the current process which match STRING.."
476  (setq string (string string))
477  (let ((matches nil))
478    (maphash (lambda(key value) 
479               (declare (ignore key))
480               (loop for class in value
481                  when (search string class :test 'string-equal)
482                  do (pushnew (list class "Java Class") matches :test 'equal)))
483             *class-name-to-full-case-insensitive*)
484    (loop for (match type) in (sort matches 'string-lessp :key 'car)
485       do (format t "~a: ~a~%" match type))
486    ))
487
488(defun jclass-method-names (class &optional full)
489  (if (java-object-p class)
490      (if (equal (jclass-name (jobject-class class)) "java.lang.Class")
491          (setq class (jclass-name class))
492          (setq class (jclass-name (jobject-class class)))))
493  (union
494   (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getMethods" (find-java-class class))) :test 'equal)
495   (ignore-errors (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getConstructors" (find-java-class class))) :test 'equal))))
496
497(defun java-class-method-names (class &optional stream)
498  "Return a list of the public methods encapsulated by the JVM CLASS.
499
500If STREAM non-nil, output a verbose description to the named output stream.
501
502CLASS may either be a string naming a fully qualified JVM class in dot
503notation, or a symbol resolved against all class entries in the
504current classpath."
505  (if stream
506      (dolist (method (jclass-method-names class t))
507        (format stream "~a~%" method))
508      (jclass-method-names class)))
509
510(setf (symbol-function 'jcmn) #'java-class-method-names)
511
512(defun path-to-class (classname)
513  (let ((full (lookup-class-name classname)))
514    (#"toString" 
515     (#"getResource" 
516      (find-java-class full)
517      (concatenate 'string "/" (substitute #\/ #\. full) ".class")))))
518
519;; http://www.javaworld.com/javaworld/javaqa/2003-07/02-qa-0725-classsrc2.html
520
521(defun all-loaded-classes ()
522  (let ((classes-field 
523         (find "classes" (#"getDeclaredFields" (jclass "java.lang.ClassLoader"))
524               :key #"getName" :test 'equal)))
525    (#"setAccessible" classes-field +true+)
526    (loop for classloader in (mapcar #'first (dump-classpath))
527       append
528         (loop with classesv = (#"get" classes-field classloader)
529            for i below (#"size" classesv)
530            collect (#"getName" (#"elementAt" classesv i)))
531       append
532         (loop with classesv = (#"get" classes-field (#"getParent" classloader))
533            for i below (#"size" classesv)
534            collect (#"getName" (#"elementAt" classesv i))))))
535
536(defun get-dynamic-class-path ()
537  (rest 
538   (find-if (lambda (loader) 
539              (string= "org.armedbear.lisp.JavaClassLoader"
540                       (jclass-name (jobject-class loader))))
541            (dump-classpath)
542            :key #'car)))
543
544(defun java-gc ()
545  (#"gc" (#"getRuntime" 'java.lang.runtime))
546  (#"runFinalization" (#"getRuntime" 'java.lang.runtime))
547  (#"gc" (#"getRuntime" 'java.lang.runtime))
548  (java-room))
549
550(defun java-room ()
551  (let ((rt (#"getRuntime" 'java.lang.runtime)))
552    (values (- (#"totalMemory" rt) (#"freeMemory" rt))
553            (#"totalMemory" rt)
554            (#"freeMemory" rt)
555            (list :used :total :free))))
556
557(defun verbose-gc (&optional (new-value nil new-value-supplied))
558  (if new-value-supplied
559      (progn (#"setVerbose" (#"getMemoryMXBean"  'java.lang.management.ManagementFactory) new-value) new-value)
560      (#"isVerbose" (#"getMemoryMXBean"  'java.lang.management.ManagementFactory))))
561
562(defun all-jars-below (directory) 
563  (loop with q = (system:list-directory directory) 
564     while q for top = (pop q)
565     if (null (pathname-name top)) do (setq q (append q (all-jars-below top))) 
566     if (equal (pathname-type top) "jar") collect top))
567
568(defun all-classfiles-below (directory) 
569  (loop with q = (system:list-directory directory) 
570     while q for top = (pop q)
571     if (null (pathname-name top)) do (setq q (append q (all-classfiles-below top ))) 
572     if (equal (pathname-type top) "class")
573     collect top
574       ))
575
576(defun all-classes-below-directory (directory)
577  (loop for file in (all-classfiles-below directory) collect
578       (format nil "~{~a.~}~a"
579               (subseq (pathname-directory file) (length (pathname-directory directory)))
580               (pathname-name file))
581       ))
582
583(defun classfiles-import (directory)
584  "Load all Java classes recursively contained under DIRECTORY in the current process."
585  (setq directory (truename directory))
586  (loop for full-class-name in (all-classes-below-directory directory)
587     for name = (#"replaceAll" full-class-name "^.*\\." "")
588     do
589       (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
590                :test 'equal)))
591
592(defun jclass-all-interfaces (class)
593  "Return a list of interfaces the class implements"
594  (unless (java-object-p class)
595    (setq class (find-java-class class)))
596  (loop for aclass = class then (#"getSuperclass" aclass)
597     while aclass
598     append (coerce (#"getInterfaces" aclass) 'list)))
599
600(defun safely (f name)
601  (let ((fname (gensym)))
602    (compile fname
603             `(lambda(&rest args)
604                (with-simple-restart (top-level
605                                      "Return from lisp method implementation for ~a." ,name)
606                  (apply ,f args))))
607    (symbol-function fname)))
608
609(defun jdelegating-interface-implementation (interface dispatch-to &rest method-names-and-defs)
610  "Creates and returns an implementation of a Java interface with
611   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
612
613   INTERFACE is an interface
614
615   DISPATCH-TO is an existing Java object
616
617   METHOD-NAMES-AND-DEFS is an alternating list of method names
618   (strings) and method definitions (closures).
619
620   For missing methods, a dummy implementation is provided that
621   calls the method on DISPATCH-TO."
622  (let ((implemented-methods
623         (loop for m in method-names-and-defs
624            for i from 0
625            if (evenp i) 
626            do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
627            else
628            do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
629    (let ((safe-method-names-and-defs 
630           (loop for (name function) on method-names-and-defs by #'cddr
631              collect name collect (safely function name))))
632      (loop for method across
633           (jclass-methods interface :declared nil :public t)
634         for method-name = (jmethod-name method)
635         when (not (member method-name implemented-methods :test #'string=))
636         do
637           (let* ((def  `(lambda
638                             (&rest args)
639                           (invoke-restargs ,(jmethod-name method) ,dispatch-to args t)
640                           )))
641             (push (coerce def 'function) safe-method-names-and-defs)
642             (push method-name safe-method-names-and-defs)))
643      (apply #'java::%jnew-proxy  interface safe-method-names-and-defs))))
644
645
Note: See TracBrowser for help on using the repository browser.