[plt-scheme] Reflection in class.ss

From: Daniel Yoo (dyoo at cs.wpi.edu)
Date: Thu Mar 29 14:07:15 EDT 2007


> I had a play with the get-field-at-runtime approach you mentioned. It 
> seems to work fine until inheritance is bought into play. See my 
> adaptation of your example below for more information ... the last line 
> raises an exception:


Hi Dave,


Yeah, get-runtime-field wasn't handling inheritance, and it wasn't doing 
any kind of error trapping.  Here's one version that tries to do so, 
although it hasn't been tested:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   ;; get-runtime-field: object symbol -> any
   ;; Tries to get the field value from the object.
   ;; We must be able to inspect the class, or else this fails.
   (define (get-runtime-field obj name)
     (let-values ([(class skipped) (object-info obj)])
       (let loop ([class class])
         (unless class
           (error 'get-runtime-field "can't inpect class for ~s" obj))
         (let*-values ([(name-symbol
                         field-k
                         field-name-list
                         field-accessor-proc
                         field-mutator-proc
                         super-class
                         skipped)
                        (class-info class)]
                       [(index) (list-index (lambda (x) (eq? x name))
                                            field-name-list)])
           (cond
             [(not index)
              (error 'get-runtime-field "unknown field ~s" name)]
             [(>= index field-k)
              (loop super-class)]
             [else
              (field-accessor-proc obj index)])))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Posted on the users mailing list.