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