Mark Karpov
Mark Karpov

Reputation: 7599

Checking parent class of an object

I would like to know a way how to check if an object is of certain class, or derived from it. E.g.:

(defclass a nil
  nil)

(defclass b (a)
  nil)

(defparameter *foo* (make-instance 'b))

(my-function *foo* 'a) ; => t
(my-function *foo* 'b) ; => t

Alternatively, a function that returns list of all base classes for a given object (or class) would be also appreciated.

Upvotes: 1

Views: 520

Answers (2)

user1597986
user1597986

Reputation: 103

You need to use MOP's (MetaObject Protocol) `class-direct-superclasses'

Quickload the library closer-mop and use `class-direct-superclasses' like so:

CL-USER> (closer-mop:class-direct-superclasses (find-class 'number))
(#<BUILT-IN-CLASS T>)
CL-USER>

If you have an instance of a class, you can do

CL-USER> (let ((table (make-instance 'test-table-2)))
           (class-direct-superclasses (class-of table)))
(#<STANDARD-CLASS STANDARD-OBJECT>)} 
CL-USER>

A possible gotcha (documented in the library): If you DEFPACKGE that :USEs closer-mop, instead of using CL, :USE closer-common-lisp

Upvotes: 0

Rainer Joswig
Rainer Joswig

Reputation: 139261

Use typep:

CL-USER 4 > (typep *foo* 'a)
T

CL-USER 5 > (typep *foo* 'b)
T

Upvotes: 7

Related Questions