Bal*_*ala 11 lisp java reflection introspection common-lisp
Java的java.lang.Class类有一个getDeclaredFields方法,它将返回给定类中的所有字段.Common Lisp有类似的东西吗?在阅读了成功的Lisp第10章(http://www.psg.com/~dlamkins/sl/chapter10.html)中的说明之后,我遇到了一些有用的函数,比如describe,inspect和symbol-plist .但是他们都不会像getDeclaredFields那样做.
dmi*_*_vk 11
您应该使用类槽和/或类直接槽(两者都来自CLOS Metaobject Protocol,MOP).class-slots返回给定类中存在的所有槽,而class-direct-slots返回在类定义中声明的所有槽.
不同的lisp实现稍微不同地实现MOP; 使用closer-mop包来实现与MOP的统一接口.
例:
(defclass foo ()
(foo-x))
(finalize-inheritance (find-class 'foo)) ;this is needed to be able to query class slots and other properties. Or, class is automatically finalized when its first instance is created
(class-slots (find-class 'foo))
=> (#<STANDARD-EFFECTIVE-SLOT-DEFINITION FOO-X>)
(slot-definition-name (first (class-slots (find-class 'foo))))
=> FOO-X
Run Code Online (Sandbox Code Playgroud)
示例:
(defun inspect (( object standard-object))
(inspect-rec (class-slots (class-of object)) object) )
(defun inspect-rec (slots o)
( if(atom slots) ()
(let ((sn (slot-definition-name (car slots)))) (cons (list sn '=> ( slot-value o sn) ) ( inspect-rec (cdr slots) o)))))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1431 次 |
最近记录: |