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

Last change on this file was 15196, checked in by Mark Evenson, 14 months ago

1.6.0-rc-0: metadata updates for the release of the Seventh edition

File size: 30.3 KB
1;; Copyright (C) 2005 Alan Ruttenberg
2;; Copyright (C) 2011-2 Mark Evenson
4;; Since JSS 1.0 was largely derivative of the Jscheme System, the
5;; current system is licensed under the same terms, namely:
7;; This software is provided 'as-is', without any express or
8;; implied warranty.
10;; In no event will the author be held liable for any damages
11;; arising from the use of this software.
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:
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.
24;; 2. Altered source versions must be plainly marked as such, and
25;;    must not be misrepresented as being the original software.
27;; 3. This notice may not be removed or altered from any source
28;;    distribution.
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.
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:
43;; (let ((sw (new 'StringWriter)))
44;;   (#"write" sw "Hello ")
45;;   (#"write" sw "World")
46;;   (print (#"toString" sw)))
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;; You could also have written (new
54;; 'io.stringwriter), (new '|io.StringWriter|), (new
55;; '
57;; the call (#"write" sw "Hello "), uses the code in 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.
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.
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")))
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.
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)
81;; (japropos string) finds all class names matching string
82;; (jcmn class-name) lists the names of all methods for the class
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
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
102;; changelog
104;; Sat January 28, 2006, alanr:
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)
114;; Split class path by ";" in addition to ":" for windows.
116;; Tested on windows, linux.
118;; 2011-05-21 Mark Evenson
119;;   "ported" to native ABCL without needing the jscheme.jar or bsh-2.0b4.jar
121(in-package :jss)
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  (defvar *muffle-warnings* t
127    "Attempt to make JSS less chatting about how things are going.")
128  (defvar *imports-resolved-classes* (make-hash-table :test 'equalp)
129    "Hashtable of all resolved imports by the current process."))
131(defun find-java-class (name)
132  "Returns the java.lang.Class representation of NAME.
134NAME can either string or a symbol according to the usual JSS conventions."
135  (jclass (maybe-resolve-class-against-imports name)))
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       )))
145(defun clear-invoke-imports ()
146  (clrhash *imports-resolved-classes*))
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)))))
157(defvar *class-name-to-full-case-insensitive* (make-hash-table :test 'equalp))
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.
166(defun invoke (method object &rest args)
167  (invoke-restargs method object args))
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))))))
184(defconstant +set-accessible+ 
185  (jmethod "java.lang.reflect.AccessibleObject" "setAccessible" "boolean"))
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))
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.
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))
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.
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.
227Use this macro if you are making a lot of calls and
228want to avoid the overhead of the dynamic dispatch."
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)))))))
249(defvar *class-lookup-overrides*)
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))
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))))))
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))))))))))
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           ))))
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))))
335(defun new (class-name &rest args)
336  "Invoke the Java constructor for CLASS-NAME with ARGS.
338CLASS-NAME may either be a symbol or a string according to the usual JSS conventions."
339  (invoke-restargs 'new class-name args))
341(defvar *running-in-osgi* (ignore-errors (jclass "org.osgi.framework.BundleActivator")))
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  )
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))))
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)
390(defun get-declared-field (class fieldname)
391  (find fieldname (#"getDeclaredFields" class)
392        :key 'jfield-name :test 'equal))
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)))))
420(defun (setf get-java-field) (value object field &optional (try-harder *running-in-osgi*))
421  (set-java-field object field value try-harder))
423(defconstant +for-name+ 
424  (jmethod "java.lang.Class" "forName" "java.lang.String" "boolean" "java.lang.ClassLoader"))
426(defun find-java-class (name)
427  (or (jstatic +for-name+ "java.lang.Class" 
428               (maybe-resolve-class-against-imports name) +true+ java::*classloader*)
429      (ignore-errors (jclass (maybe-resolve-class-against-imports name)))))
431(defmethod print-object ((obj (jclass "java.lang.Class")) stream) 
432  (print-unreadable-object (obj stream :identity nil)
433    (format stream "java class ~a" (jclass-name obj))))
435(defmethod print-object ((obj (jclass "java.lang.reflect.Method")) stream) 
436  (print-unreadable-object (obj stream :identity nil)
437    (format stream "method ~a" (#"toString" obj))))
439(defun do-auto-imports ()
440  (if (sys::system-artifacts-are-jars-p)
441      (do-auto-imports-from-jars)
442      (progn
443        ;;; First, import all the classes available from the module system
444        (do-auto-imports-from-modules)
445        ;;; Then, introspect any jars that appear on the classpath
446        (loop :for entry :in (second (multiple-value-list (sys::java.class.path)))
447             :doing (let ((p (pathname entry)))
448                      (when (string-equal (pathname-type p) "jar")
449                        (jar-import p)))))))
451(defun do-auto-imports-from-modules ()
452  (loop :for (name . full-class-name) :in (all-class-names-from-modules)
453     :doing
454       (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
455                :test 'equal)))
457(defun all-class-names-from-modules ()
458  (let ((class-pattern (jstatic "compile" "java.util.regex.Pattern" ".*\\.class$"))
459        (name-pattern (jstatic "compile" "java.util.regex.Pattern" ".*?([^.]*)$")))
460    (loop
461       :for module :across (chain (jstatic "boot" "java.lang.ModuleLayer")
462                                  "configuration" "modules" "stream" "toArray")
463       :appending
464         (loop
465            :for class-as-path :across (chain module "reference" "open" "list" "toArray")
466            :when
467              (jcall "matches" (jcall "matcher" class-pattern class-as-path))
468            :collect
469              (let* ((full-name (jcall "substring" (jcall "replace" class-as-path #\/ #\.)
470                                           0
471                                           (- (jcall "length" class-as-path) (jcall "length" ".class"))))
472                     (matcher (jcall "matcher" name-pattern full-name))
473                     (name (progn
474                             (jcall "matches" matcher)
475                             (jcall "group" matcher 1))))
476                (cons name full-name))))))
478(defun do-auto-imports-from-jars ()
479  (labels ((expand-paths (cp)
480             (loop :for s :in cp
481                :appending (loop :for entry 
482                              :in (let ((p (pathname s)))
483                                    (if (wild-pathname-p p)
484                                        (directory p)
485                                        (list p)))
486                              :collecting entry)))
487           (import-classpath (cp)
488             (mapcar 
489              (lambda (p) 
490                (when *load-verbose*
491                  (format t ";; Importing ~A~%" p))
492                (cond 
493                  ((file-directory-p p) )
494                  ((equal (pathname-type p) "jar")
495                   (jar-import (merge-pathnames p
496                                                (format nil "~a/" (jstatic "getProperty" "java.lang.System" "user.dir")))))))
497              cp))
498           (split-classpath (cp)
499             (coerce 
500              (jcall "split" cp 
501                     (string (jfield (jclass "") "pathSeparatorChar")))
502              'cons))
503           (do-imports (cp)
504             (import-classpath (expand-paths (split-classpath cp)))))
506    (let ((mx-bean (jstatic "getRuntimeMXBean"
507                            '||)))
508      (do-imports (jcall "getClassPath" mx-bean))
509      (do-imports (jcall "getBootClassPath" mx-bean)))))
511(eval-when (:load-toplevel :execute)
512  (when *do-auto-imports* 
513    (do-auto-imports)))
515(defun japropos (string)
516  "Output the names of all Java class names loaded in the current process which match STRING.."
517  (setq string (string string))
518  (let ((matches nil))
519    (maphash (lambda(key value) 
520               (declare (ignore key))
521               (loop for class in value
522                  when (search string class :test 'string-equal)
523                  do (pushnew (list class "Java Class") matches :test 'equal)))
524             *class-name-to-full-case-insensitive*)
525    (loop for (match type) in (sort matches 'string-lessp :key 'car)
526       do (format t "~a: ~a~%" match type))
527    ))
529(defun jclass-method-names (class &optional full)
530  (if (java-object-p class)
531      (if (equal (jclass-name (jobject-class class)) "java.lang.Class")
532          (setq class (jclass-name class))
533          (setq class (jclass-name (jobject-class class)))))
534  (union
535   (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getMethods" (find-java-class class))) :test 'equal)
536   (ignore-errors (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getConstructors" (find-java-class class))) :test 'equal))))
538(defun java-class-method-names (class &optional stream)
539  "Return a list of the public methods encapsulated by the JVM CLASS.
541If STREAM non-nil, output a verbose description to the named output stream.
543CLASS may either be a string naming a fully qualified JVM class in dot
544notation, or a symbol resolved against all class entries in the
545current classpath."
546  (if stream
547      (dolist (method (jclass-method-names class t))
548        (format stream "~a~%" method))
549      (jclass-method-names class)))
551(setf (symbol-function 'jcmn) #'java-class-method-names)
553(defun path-to-class (classname)
554  (let ((full (lookup-class-name classname)))
555    (#"toString" 
556     (#"getResource" 
557      (find-java-class full)
558      (concatenate 'string "/" (substitute #\/ #\. full) ".class")))))
562(defun all-loaded-classes ()
563  (let ((classes-field 
564         (find "classes" (#"getDeclaredFields" (jclass "java.lang.ClassLoader"))
565               :key #"getName" :test 'equal)))
566    (#"setAccessible" classes-field +true+)
567    (loop for classloader in (mapcar #'first (dump-classpath))
568       append
569         (loop with classesv = (#"get" classes-field classloader)
570            for i below (#"size" classesv)
571            collect (#"getName" (#"elementAt" classesv i)))
572       append
573         (loop with classesv = (#"get" classes-field (#"getParent" classloader))
574            for i below (#"size" classesv)
575            collect (#"getName" (#"elementAt" classesv i))))))
577(defun get-dynamic-class-path ()
578  (rest 
579   (find-if (lambda (loader) 
580              (string= "org.armedbear.lisp.JavaClassLoader"
581                       (jclass-name (jobject-class loader))))
582            (dump-classpath)
583            :key #'car)))
585(defun java-gc ()
586  (#"gc" (#"getRuntime" 'java.lang.runtime))
587  (#"runFinalization" (#"getRuntime" 'java.lang.runtime))
588  (#"gc" (#"getRuntime" 'java.lang.runtime))
589  (java-room))
591(defun java-room ()
592  (let ((rt (#"getRuntime" 'java.lang.runtime)))
593    (values (- (#"totalMemory" rt) (#"freeMemory" rt))
594            (#"totalMemory" rt)
595            (#"freeMemory" rt)
596            (list :used :total :free))))
598(defun verbose-gc (&optional (new-value nil new-value-supplied))
599  (if new-value-supplied
600      (progn (#"setVerbose" (#"getMemoryMXBean"  ' new-value) new-value)
601      (#"isVerbose" (#"getMemoryMXBean"  '
603(defun all-jars-below (directory) 
604  (loop with q = (system:list-directory directory) 
605     while q for top = (pop q)
606     if (null (pathname-name top)) do (setq q (append q (all-jars-below top))) 
607     if (equal (pathname-type top) "jar") collect top))
609(defun all-classfiles-below (directory) 
610  (loop with q = (system:list-directory directory) 
611     while q for top = (pop q)
612     if (null (pathname-name top)) do (setq q (append q (all-classfiles-below top ))) 
613     if (equal (pathname-type top) "class")
614     collect top
615       ))
617(defun all-classes-below-directory (directory)
618  (loop for file in (all-classfiles-below directory) collect
619       (format nil "~{~a.~}~a"
620               (subseq (pathname-directory file) (length (pathname-directory directory)))
621               (pathname-name file))
622       ))
624(defun classfiles-import (directory)
625  "Load all Java classes recursively contained under DIRECTORY in the current process."
626  (setq directory (truename directory))
627  (loop for full-class-name in (all-classes-below-directory directory)
628     for name = (#"replaceAll" full-class-name "^.*\\." "")
629     do
630       (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
631                :test 'equal)))
633(defun jclass-all-interfaces (class)
634  "Return a list of interfaces the class implements"
635  (unless (java-object-p class)
636    (setq class (find-java-class class)))
637  (loop for aclass = class then (#"getSuperclass" aclass)
638     while aclass
639     append (coerce (#"getInterfaces" aclass) 'list)))
641(defun safely (f name)
642  (let ((fname (gensym)))
643    (compile fname
644             `(lambda(&rest args)
645                (with-simple-restart (top-level
646                                      "Return from lisp method implementation for ~a." ,name)
647                  (apply ,f args))))
648    (symbol-function fname)))
650(defun jdelegating-interface-implementation (interface dispatch-to &rest method-names-and-defs)
651  "Creates and returns an implementation of a Java interface with
652   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
654   INTERFACE is an interface
656   DISPATCH-TO is an existing Java object
658   METHOD-NAMES-AND-DEFS is an alternating list of method names
659   (strings) and method definitions (closures).
661   For missing methods, a dummy implementation is provided that
662   calls the method on DISPATCH-TO."
663  (let ((implemented-methods
664         (loop for m in method-names-and-defs
665            for i from 0
666            if (evenp i) 
667            do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
668            else
669            do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
670    (let ((safe-method-names-and-defs 
671           (loop for (name function) on method-names-and-defs by #'cddr
672              collect name collect (safely function name))))
673      (loop for method across
674           (jclass-methods interface :declared nil :public t)
675         for method-name = (jmethod-name method)
676         when (not (member method-name implemented-methods :test #'string=))
677         do
678           (let* ((def  `(lambda
679                             (&rest args)
680                           (invoke-restargs ,(jmethod-name method) ,dispatch-to args t)
681                           )))
682             (push (coerce def 'function) safe-method-names-and-defs)
683             (push method-name safe-method-names-and-defs)))
684      (apply #'java::%jnew-proxy  interface safe-method-names-and-defs))))
Note: See TracBrowser for help on using the repository browser.