Clojure是否等效于ruby的#methods方法?

时间:2019-09-18 04:53:54

标签: ruby clojure functional-programming

在ruby中,我们可以执行Object.methods来获取特定Object或类的所有方法。

例如:

irb(main):001:0> Object.methods
=> [:new, :allocate, :superclass, :<=>, :include, :<=, :>=, :==, :===, :included_modules, :include?, :name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods, :private_instance_methods, :constants, :const_get, :const_set, :const_defined?, :class_variables, :remove_class_variable, :class_variable_get, :class_variable_set, :class_variable_defined?, :public_constant, :private_constant, :deprecate_constant, :singleton_class?, :module_exec, :class_exec, :freeze, :inspect, :const_missing, :class_eval, :method_defined?, :public_method_defined?, :prepend, :<, :>, :private_method_defined?, :protected_method_defined?, :public_class_method, :module_eval, :to_s, :private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method, :instance_of?, :kind_of?, :is_a?, :tap, :public_send, :remove_instance_variable, :instance_variable_set, :method, :public_method, :singleton_method, :extend, :define_singleton_method, :to_enum, :enum_for, :=~, :!~, :eql?, :respond_to?, :object_id, :send, :display, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variable_get, :instance_variables, :instance_variable_defined?, :!, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

我们可以在Clojure repl中做类似的事情吗(例如:leiningen)?

2 个答案:

答案 0 :(得分:7)

How to list the functions of a namespace?,这是一个类似的问题,请转到链接以获取完整说明。

在Clojure中,我们没有类,但是函数被分组到名称空间中。使用ns-publics可以获得该命名空间中所有功能的映射。

(keys (ns-publics 'user))
; => (clojuredocs help find-name user.proxy$java.lang.Object$SignalHandler$d8c00ec7 cdoc apropos-better)

答案 1 :(得分:3)

要获取Java对象的方法,可以使用clojure.reflect

(map (comp keyword :name) (:members (clojure.reflect/reflect Object))))
;; => (:getClass :wait :finalize :java.lang.Object :equals :notifyAll :hashCode :toString :registerNatives :clone :notify :wait :wait)

有关更多建议,请参见How can I get the methods of a Java class from Clojure?