java.lisp 24.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
;;; java.lisp
;;;
;;; Copyright (C) 2003-2007 Peter Graves, Andras Simon
;;; $Id$
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License
;;; as published by the Free Software Foundation; either version 2
;;; of the License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module.  An independent module is a module which is not derived from
;;; or based on this library.  If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so.  If you do not wish to do so, delete this
;;; exception statement from your version.

(in-package "JAVA")

(require "CLOS")
35
(require "PRINT-OBJECT")
36

37 38
(defvar *classloader* (get-default-classloader))

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54


(EXPORT '(JREGISTER-HANDLER JINTERFACE-IMPLEMENTATION JMAKE-INVOCATION-HANDLER
          JMAKE-PROXY JPROPERTY-VALUE JOBJECT-CLASS JCLASS-SUPERCLASS
          JCLASS-INTERFACES JCLASS-INTERFACE-P JCLASS-SUPERCLASS-P
          JCLASS-ARRAY-P JARRAY-COMPONENT-TYPE JARRAY-LENGTH
          JNEW-ARRAY-FROM-ARRAY JNEW-ARRAY-FROM-LIST JARRAY-FROM-LIST
          JCLASS-CONSTRUCTORS JCONSTRUCTOR-PARAMS JCLASS-FIELD JCLASS-FIELDS
          JFIELD-TYPE JFIELD-NAME JCLASS-METHODS JMETHOD-PARAMS JMETHOD-NAME
          JINSTANCE-OF-P JMEMBER-STATIC-P JMEMBER-PUBLIC-P JMEMBER-PROTECTED-P
          JNEW-RUNTIME-CLASS DEFINE-JAVA-CLASS ENSURE-JAVA-CLASS CHAIN
          JMETHOD-LET JEQUAL))




55 56 57 58 59 60 61
(defun add-url-to-classpath (url &optional (classloader *classloader*))
  (jcall "addUrl" classloader url))

(defun add-urls-to-classpath (&rest urls)
  (dolist (url urls)
    (add-url-to-classpath url)))

62 63 64 65 66
(defgeneric add-to-classpath (jar-or-jars &optional classloader)
  (:documentation "Add JAR-OR-JARS to the JVM classpath optionally specifying the CLASSLOADER to add.

JAR-OR-JARS is either a pathname designating a jar archive or the root
directory to search for classes or a list of such values."))
67 68 69 70

(defmethod add-to-classpath (jar-or-jars &optional (classloader (get-current-classloader)))
  (%add-to-classpath jar-or-jars classloader))

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
(defun jregister-handler (object event handler &key data count)
  (%jregister-handler object event handler data count))

(defun jinterface-implementation (interface &rest method-names-and-defs)
  "Creates and returns an implementation of a Java interface with
   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.

   INTERFACE is either a Java interface or a string naming one.

   METHOD-NAMES-AND-DEFS is an alternating list of method names
   (strings) and method definitions (closures).

   For missing methods, a dummy implementation is provided that
   returns nothing or null depending on whether the return type is
   void or not. This is for convenience only, and a warning is issued
   for each undefined method."
  (let ((interface (jclass interface))
        (implemented-methods
         (loop for m in method-names-and-defs
           for i from 0
           if (evenp i)
           do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
           else
94
           do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
95 96 97 98 99 100 101 102 103 104
    (loop for method across
      (jclass-methods interface :declared nil :public t)
      for method-name = (jmethod-name method)
      when (not (member method-name implemented-methods :test #'string=))
      do
      (let* ((void-p (string= (jclass-name (jmethod-return-type method)) "void"))
             (arglist (when (plusp (length (jmethod-params method))) '(&rest ignore)))
             (def `(lambda
                     ,arglist
                     ,(when arglist '(declare (ignore ignore)))
105
                     ,(if void-p '(values) java:+null+))))
106 107 108 109 110 111
        (warn "Implementing dummy method ~a for interface ~a"
              method-name (jclass-name interface))
        (push (coerce def 'function) method-names-and-defs)
        (push method-name method-names-and-defs)))
    (apply #'%jnew-proxy interface method-names-and-defs)))

112 113 114 115 116 117 118
(defun jmake-invocation-handler (function)
  (%jmake-invocation-handler function))

(when (autoloadp 'jmake-proxy)
  (fmakunbound 'jmake-proxy))

(defgeneric jmake-proxy (interface implementation &optional lisp-this)
119 120 121 122 123 124 125
  (:documentation "Returns a proxy Java object implementing the provided interface(s) using methods implemented in Lisp - typically closures, but implementations are free to provide other mechanisms. You can pass an optional 'lisp-this' object that will be passed to the implementing methods as their first argument. If you don't provide this object, NIL will be used. The second argument of the Lisp methods is the name of the Java method being implemented. This has the implication that overloaded methods are merged, so you have to manually discriminate them if you want to. The remaining arguments are java-objects wrapping the method's parameters."))

(defun canonicalize-jproxy-interfaces (ifaces)
  (if (listp ifaces)
      (mapcar #'jclass ifaces)
      (list (jclass ifaces))))

126 127 128

(defmethod jmake-proxy (interface invocation-handler &optional lisp-this)
  "Basic implementation that directly uses an invocation handler."
129
  (%jmake-proxy (canonicalize-jproxy-interfaces interface) invocation-handler lisp-this))
130 131 132

(defmethod jmake-proxy (interface (implementation function) &optional lisp-this)
  "Implements a Java interface forwarding method calls to a Lisp function."
133
  (%jmake-proxy (canonicalize-jproxy-interfaces interface) (jmake-invocation-handler implementation) lisp-this))
134 135 136 137 138 139 140 141 142 143 144 145 146

(defmethod jmake-proxy (interface (implementation package) &optional lisp-this)
  "Implements a Java interface mapping Java method names to symbols in a given package. javaMethodName is mapped to a JAVA-METHOD-NAME symbol. An error is signaled if no such symbol exists in the package, or if the symbol exists but does not name a function."
  (flet ((java->lisp (name)
	   (with-output-to-string (str)
	     (let ((last-lower-p nil))
	       (map nil (lambda (char)
			  (let ((upper-p (char= (char-upcase char) char)))
			    (when (and last-lower-p upper-p)
			      (princ "-" str))
			    (setf last-lower-p (not upper-p))
			    (princ (char-upcase char) str)))
		    name)))))
147
    (%jmake-proxy (canonicalize-jproxy-interfaces interface)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
		  (jmake-invocation-handler 
		   (lambda (obj method &rest args)
		     (let ((sym (find-symbol
				 (java->lisp method)
				 implementation)))
		       (unless sym
			 (error "Symbol ~A, implementation of method ~A, not found in ~A"
				  (java->lisp method)
				  method
				  implementation))
			 (if (fboundp sym)
			     (apply (symbol-function sym) obj method args)
			     (error "Function ~A, implementation of method ~A, not found in ~A"
				    sym method implementation)))))
		  lisp-this)))

(defmethod jmake-proxy (interface (implementation hash-table) &optional lisp-this)
  "Implements a Java interface using closures in an hash-table keyed by Java method name."
166
  (%jmake-proxy (canonicalize-jproxy-interfaces interface)
167 168 169 170 171 172 173 174 175
		(jmake-invocation-handler 
		 (lambda (obj method &rest args)
		   (let ((fn (gethash method implementation)))
		     (if fn
			 (apply fn obj args)
			 (error "Implementation for method ~A not found in ~A"
				method implementation)))))
		lisp-this))

176 177 178 179 180
(defun jequal (obj1 obj2)
  "Compares obj1 with obj2 using java.lang.Object.equals()"
  (jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
	 obj1 obj2))

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
(defun jobject-class (obj)
  "Returns the Java class that OBJ belongs to"
  (jcall (jmethod "java.lang.Object" "getClass") obj))

(defun jclass-superclass (class)
  "Returns the superclass of CLASS, or NIL if it hasn't got one"
  (jcall (jmethod "java.lang.Class" "getSuperclass") (jclass class)))

(defun jclass-interfaces (class)
  "Returns the vector of interfaces of CLASS"
  (jcall (jmethod "java.lang.Class" "getInterfaces") (jclass class)))

(defun jclass-interface-p (class)
  "Returns T if CLASS is an interface"
  (jcall (jmethod "java.lang.Class" "isInterface") (jclass class)))

(defun jclass-superclass-p (class-1 class-2)
  "Returns T if CLASS-1 is a superclass or interface of CLASS-2"
  (jcall (jmethod "java.lang.Class" "isAssignableFrom" "java.lang.Class")
         (jclass class-1)
         (jclass class-2)))

(defun jclass-array-p (class)
  "Returns T if CLASS is an array class"
  (jcall (jmethod "java.lang.Class" "isArray") (jclass class)))

(defun jarray-component-type (atype)
  "Returns the component type of the array type ATYPE"
  (assert (jclass-array-p atype))
  (jcall (jmethod "java.lang.Class" "getComponentType") atype))

(defun jarray-length (java-array)
213
  "Returns the length of a Java primitive array."
214 215 216 217 218 219 220
  (jstatic "getLength" "java.lang.reflect.Array" java-array)  )

(defun (setf jarray-ref) (new-value java-array &rest indices)
  (apply #'jarray-set java-array new-value indices))

(defun jnew-array-from-array (element-type array)
  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
221
   initialized from ARRAY."
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  (flet
    ((row-major-to-index (dimensions n)
                         (loop for dims on dimensions
                           with indices
                           do
                           (multiple-value-bind (m r) (floor n (apply #'* (cdr dims)))
                             (push m indices)
                             (setq n r))
                           finally (return (nreverse indices)))))
    (let* ((fill-pointer (when (array-has-fill-pointer-p array) (fill-pointer array)))
           (dimensions (if fill-pointer (list fill-pointer) (array-dimensions array)))
           (jarray (apply #'jnew-array element-type dimensions)))
      (dotimes (i (if fill-pointer fill-pointer (array-total-size array)) jarray)
        #+maybe_one_day
        (setf (apply #'jarray-ref jarray (row-major-to-index dimensions i)) (row-major-aref array i))
        (apply #'(setf jarray-ref) (row-major-aref array i) jarray (row-major-to-index dimensions i))))))

239
(defun jnew-array-from-list (element-type list)
240 241
  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
   initialized from a Lisp list."
242 243 244 245 246 247 248
  (let ((jarray (jnew-array element-type (length list)))
	(i 0))
    (dolist (x list)
      (setf (jarray-ref jarray i) x
	    i (1+ i)))
    jarray))

249 250 251 252 253 254 255 256
(defun jarray-from-list (list)
  "Return a Java array from LIST whose type is inferred from the first element.

For more control over the type of the array, use JNEW-ARRAY-FROM-LIST."
  (jnew-array-from-list
   (jobject-class (first list))
   list))

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
(defun list-from-jarray (jarray)
  "Returns a list with the elements of `jarray`."
  (loop for i from 0 below (jarray-length jarray)
        collect (jarray-ref jarray i)))

(defun vector-from-jarray (jarray)
  "Returns a vector with the elements of `jarray`."
  (loop with vec = (make-array (jarray-length jarray))
        for i from 0 below (jarray-length jarray)
        do (setf (aref vec i) (jarray-ref jarray i))
        finally (return vec)))

(defun list-from-jenumeration (jenumeration)
  "Returns a list with the elements returned by successive `nextElement`
calls on the java.util.Enumeration `jenumeration`."
  (loop while (jcall jenumeration
                     (jmethod "java.util.Enumeration" "hasMoreElements"))
        collect (jcall jenumeration
                       (jmethod "java.util.Enumeration" "nextElement"))))

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
(defun jclass-constructors (class)
  "Returns a vector of constructors for CLASS"
  (jcall (jmethod "java.lang.Class" "getConstructors") (jclass class)))

(defun jconstructor-params (constructor)
  "Returns a vector of parameter types (Java classes) for CONSTRUCTOR"
  (jcall (jmethod "java.lang.reflect.Constructor" "getParameterTypes") constructor))

(defun jclass-fields (class &key declared public)
  "Returns a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) fields of CLASS"
  (let* ((getter (if declared "getDeclaredFields" "getFields"))
         (fields (jcall (jmethod "java.lang.Class" getter) (jclass class))))
    (if public (delete-if-not #'jmember-public-p fields) fields)))

(defun jclass-field (class field-name)
  "Returns the field named FIELD-NAME of CLASS"
  (jcall (jmethod "java.lang.Class" "getField" "java.lang.String")
         (jclass class) field-name))

(defun jfield-type (field)
  "Returns the type (Java class) of FIELD"
  (jcall (jmethod "java.lang.reflect.Field" "getType") field))

(defun jfield-name (field)
  "Returns the name of FIELD as a Lisp string"
  (jcall (jmethod "java.lang.reflect.Field" "getName") field))

304 305 306 307 308 309

(defun (setf jfield) (newvalue class-ref-or-field field-or-instance
		      &optional (instance nil instance-supplied-p) unused-value)
  (declare (ignore unused-value))
  (if instance-supplied-p
      (jfield class-ref-or-field field-or-instance instance newvalue)
310
      (jfield class-ref-or-field field-or-instance nil newvalue)))
311

312 313 314 315 316 317 318 319 320 321
(defun jclass-methods (class &key declared public)
  "Return a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) methods of CLASS"
  (let* ((getter (if declared "getDeclaredMethods" "getMethods"))
         (methods (jcall (jmethod "java.lang.Class" getter) (jclass class))))
    (if public (delete-if-not #'jmember-public-p methods) methods)))

(defun jmethod-params (method)
  "Returns a vector of parameter types (Java classes) for METHOD"
  (jcall (jmethod "java.lang.reflect.Method" "getParameterTypes") method))

322 323 324 325 326 327 328
(defun jmethod-return-type (method)
  "Returns the result type (Java class) of the METHOD"
  (jcall (jmethod "java.lang.reflect.Method" "getReturnType") method))

(defun jmethod-declaring-class (method)
  "Returns the Java class declaring METHOD"
  (jcall (jmethod "java.lang.reflect.Method" "getDeclaringClass") method))
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

(defun jmethod-name (method)
  "Returns the name of METHOD as a Lisp string"
  (jcall (jmethod "java.lang.reflect.Method" "getName") method))

(defun jinstance-of-p (obj class)
  "OBJ is an instance of CLASS (or one of its subclasses)"
  (and (java-object-p obj)
       (jcall (jmethod "java.lang.Class" "isInstance" "java.lang.Object") (jclass class) obj)))

(defun jmember-static-p (member)
  "MEMBER is a static member of its declaring class"
  (jstatic (jmethod "java.lang.reflect.Modifier" "isStatic" "int")
           "java.lang.reflect.Modifier"
           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))

(defun jmember-public-p (member)
  "MEMBER is a public member of its declaring class"
  (jstatic (jmethod "java.lang.reflect.Modifier" "isPublic" "int")
           "java.lang.reflect.Modifier"
           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))

(defun jmember-protected-p (member)
  "MEMBER is a protected member of its declaring class"
  (jstatic (jmethod "java.lang.reflect.Modifier" "isProtected" "int")
           "java.lang.reflect.Modifier"
           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))

(defmethod make-load-form ((object java-object) &optional environment)
  (declare (ignore environment))
  (let ((class-name (jclass-name (jclass-of object))))
    (cond
     ((string= class-name "java.lang.reflect.Constructor")
      `(java:jconstructor ,(jclass-name
                            (jcall (jmethod "java.lang.reflect.Constructor"
                                            "getDeclaringClass") object))
                          ,@(loop for arg-type across
                              (jcall
                               (jmethod "java.lang.reflect.Constructor"
                                        "getParameterTypes")
                               object)
                              collecting
                              (jclass-name arg-type))))
     ((string= class-name "java.lang.reflect.Method")
      `(java:jmethod ,(jclass-name
                       (jcall (jmethod "java.lang.reflect.Method"
                                       "getDeclaringClass") object))
                     ,(jmethod-name object)
                     ,@(loop for arg-type across
                         (jcall
                          (jmethod "java.lang.reflect.Method"
                                   "getParameterTypes")
                          object)
                         collecting
                         (jclass-name arg-type))))
384 385 386 387 388 389 390 391 392
     ((string= class-name "java.lang.reflect.Field")
      `(let ((field 
	       (find ,(jcall "getName" object) 
		     (jcall "getDeclaredFields"
			    ,(jcall "getDeclaringClass" object))
		     :key (lambda(el) (jcall "getName" el))
		     :test 'equal)))
	 (jcall "setAccessible" field t)
	 field))
393 394 395
     ((jinstance-of-p object "java.lang.Class")
      `(java:jclass ,(jcall (jmethod "java.lang.Class" "getName") object)))
     (t
396
      (error "Unknown load-form for ~A" class-name)))))
397

398 399 400
(defun jproperty-value (object property)
  "setf-able access on the Java Beans notion of property named PROPETRY on OBJECT."
  (%jget-property-value object property))
401 402 403 404

(defun (setf jproperty-value) (value obj prop)
  (%jset-property-value obj prop value))

405 406 407
;;; higher-level operators

(defmacro chain (target op &rest ops)
408 409 410 411 412 413 414 415 416 417 418
  "Performs chained method invocations. 

TARGET is either the receiver object when the first call is a virtual method
call or a list in the form (:static <jclass>) when the first method
call is a static method call. 

OP and each of the OPS are either method designators or lists in the
form (<method designator> &rest args), where a method designator is
either a string naming a method, or a jmethod object. CHAIN will
perform the method call specified by OP on TARGET; then, for each
of the OPS, CHAIN will perform the specified method call using the
419
object returned by the previous method call as the receiver, and will
420 421
ultimately return the result of the last method call.  For example,
the form:
422 423 424

  (chain (:static \"java.lang.Runtime\") \"getRuntime\" (\"exec\" \"ls\"))

425
is equivalent to the following Java code:
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

  java.lang.Runtime.getRuntime().exec(\"ls\");"
  (labels ((canonicalize-op (op) (if (listp op) op (list op)))
	   (compose-arglist (target op) `(,(car op) ,target ,@(cdr op)))
	   (make-binding-for (form) `(,(gensym) ,form))
	   (make-binding (bindings next-op &aux (target (caar bindings)))
	     (cons (make-binding-for
		    `(jcall ,@(compose-arglist target
					       (canonicalize-op next-op))))
		   bindings)))
    (let* ((first (if (and (consp target) (eq (first target) :static))
		      `(jstatic ,@(compose-arglist (cadr target) (canonicalize-op op)))
		      `(jcall ,@(compose-arglist target (canonicalize-op op)))))
	   (bindings (nreverse
		      (reduce #'make-binding ops
			      :initial-value (list (make-binding-for first))))))
      `(let* ,bindings
443 444
	 (declare (ignore ,@(butlast (mapcar #'car bindings))))
	 ,(caar (last bindings))))))
445 446 447 448 449 450 451 452 453 454 455 456

(defmacro jmethod-let (bindings &body body)
  (let ((args (gensym)))
    `(let ,(mapcar (lambda (binding)
		     `(,(car binding) (jmethod ,@(cdr binding))))
		   bindings)
       (macrolet ,(mapcar (lambda (binding)
			    `(,(car binding) (&rest ,args)
			       `(jcall ,,(car binding) ,@,args)))
			  bindings)
	 ,@body))))

457 458 459
;;; print-object

(defmethod print-object ((obj java:java-object) stream)
460 461 462
  (if (jnull-ref-p obj)
      (write-string "#<null>" stream)
      (print-java-object-by-class (intern (jclass-name (jobject-class obj)) 'keyword) obj stream)))
463 464 465 466 467 468

;;define extensions by eql methods on class name interned in keyword package
;;e.g. (defmethod java::print-java-object-by-class ((class (eql ':|uk.ac.manchester.cs.owl.owlapi.concurrent.ConcurrentOWLOntologyImpl|)) obj stream) 
;;	   (print 'hi)
;;         (call-next-method))
(defmethod print-java-object-by-class :around (class obj stream)
469 470 471 472
  (handler-bind ((java-exception #'(lambda(c)
				     (format stream "#<~a, while printing a ~a>"
					     (jcall "toString" (java-exception-cause  c))
					     (jcall "getName" (jcall "getClass" obj)))
473 474 475 476 477 478 479 480 481 482 483 484
				     (return-from print-java-object-by-class))))
    (call-next-method)))

;; we have to do our own inheritence for the java class
(defmethod print-java-object-by-class (class obj stream)
  (loop for super = class then (jclass-superclass super)
	for keyword = (intern (jcall "getName" super) 'keyword)
	for method = (find-method #'print-java-object-by-class nil (list `(eql ,keyword) t t) nil)
	while (jclass-superclass super)
	when method do (return-from print-java-object-by-class
			 (print-java-object-by-class keyword obj stream)))
  (write-string (sys::%write-to-string obj) stream))
485 486

(defmethod print-object ((e java:java-exception) stream)
487 488 489 490 491 492 493 494 495 496 497 498 499
  (handler-bind ((java-exception #'(lambda(c)
				     (format stream "#<~a,while printing a ~a>"
					     (jcall "toString" (java-exception-cause  c))
					     (jcall "getName" (jcall "getClass" e)))
				     (return-from print-object))))
    (if *print-escape*
	(print-unreadable-object (e stream :type t :identity t)
	  (format stream "~A"
		  (java:jcall (java:jmethod "java.lang.Object" "toString")
			      (java:java-exception-cause e))))
	(format stream "Java exception '~A'."
		(java:jcall (java:jmethod "java.lang.Object" "toString")
			    (java:java-exception-cause e))))))
500 501

;;; JAVA-CLASS support
502
(defconstant +java-lang-object+ (jclass "java.lang.Object"))
503 504 505 506 507 508

(defclass java-class (standard-class)
  ((jclass :initarg :java-class
	   :initform (error "class is required")
	   :reader java-class-jclass)))

509 510 511 512 513 514 515 516
;;; FIXME (rudi 2012-05-02): consider replacing the metaclass of class
;;; java-object to be java-class here instead of allowing this subclass
;;; relationship.  On the other hand, abcl ran for the longest time
;;; without an implementation of validate-superclass, so this doesn't
;;; introduce new sources for bugs.
(defmethod mop:validate-superclass ((class java-class) (superclass built-in-class))
  t)

517 518 519 520 521 522 523 524
;;init java.lang.Object class
(defconstant +java-lang-object-class+
  (%register-java-class +java-lang-object+
			(mop::ensure-class (make-symbol "java.lang.Object")
					   :metaclass (find-class 'java-class)
					   :direct-superclasses (list (find-class 'java-object))
					   :java-class +java-lang-object+)))

525 526 527 528 529 530 531
(defun jclass-additional-superclasses (jclass)
  "Extension point to put additional CLOS classes on the CPL of a CLOS Java class."
  (let ((supers nil))
    (when (jclass-interface-p jclass)
      (push (find-class 'java-object) supers))
    supers))

532
(defun ensure-java-class (jclass)
533
  "Attempt to ensure that the Java class referenced by JCLASS exists in the current process of the implementation."
534 535 536 537
  (let ((class (%find-java-class jclass)))
    (if class
	class
	(%register-java-class
538 539 540
	 jclass (mop::ensure-class
		 (make-symbol (jclass-name jclass))
		 :metaclass (find-class 'java-class)
541 542 543 544 545 546 547
		 :direct-superclasses
		 (let ((supers
			(mapcar #'ensure-java-class
				(delete nil
					(concatenate 'list
						     (list (jclass-superclass jclass))
						     (jclass-interfaces jclass))))))
548
		   (append supers (jclass-additional-superclasses jclass)))
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
		 :java-class jclass)))))

(defmethod mop::compute-class-precedence-list ((class java-class))
  "Sort classes this way:
   1. Java classes (but not java.lang.Object)
   2. Java interfaces
   3. java.lang.Object
   4. other classes
   Rationale:
   1. Concrete classes are the most specific.
   2. Then come interfaces.
     So if a generic function is specialized both on an interface and a concrete class,
     the concrete class comes first.
   3. because everything is an Object.
   4. to handle base CLOS classes.
   Note: Java interfaces are not sorted among themselves in any way, so if a
   gf is specialized on two different interfaces and you apply it to an object that
   implements both, it is unspecified which method will be called."
567
  (let ((cpl (nreverse (mop::collect-superclasses* class))))
568 569 570 571 572 573 574 575 576 577
    (flet ((score (class)
	     (if (not (typep class 'java-class))
		 4
		 (cond
		   ((jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
			   (java-class-jclass class) +java-lang-object+) 3)
		   ((jclass-interface-p (java-class-jclass class)) 2)
		   (t 1)))))
      (stable-sort cpl #'(lambda (x y)
			   (< (score x) (score y)))))))
578 579 580 581 582
	  
(defmethod make-instance ((class java-class) &rest initargs &key &allow-other-keys)
  (declare (ignore initargs))
  (error "make-instance not supported for ~S" class))

583 584 585 586
(defun jinput-stream (pathname)
  "Returns a java.io.InputStream for resource denoted by PATHNAME."
  (sys:ensure-input-stream pathname))

587
(provide "JAVA")
588