简体   繁体   English

如何在对象上调用setter方法(强制类型)

[英]how to invoke a setter method on an object (that coerces types)

I wish to write a function that interops with java objects 我希望编写一个与java对象交互的函数

(assoc-obj <object> "<Prop1>" <Val1> "<Prop2>" <Val2>)

which is the same as 这是一样的

(doto <object>
     (.set<Prop1> <Val1>)
     (.set<Prop2> <Val2>))

I'm working with reflection: 我正在使用反思:

(let [method (->> 
              (seq (.getMethods java.util.Date))
              (filter #(= "setDate" (.getName %)))
              first)
      arr (object-array 1)
      _   (aset arr 0 (int 1))
      d   (java.util.Date.)]
  (.invoke method d arr)
  d)

but I am finding that there are problems with type coercing. 但我发现类型强制存在问题。

Are there better/more clojurish ways of doing this? 这样做有更好/更多的方式吗?

I'd use clojure.lang.Reflector/invokeInstanceMethod . 我使用clojure.lang.Reflector/invokeInstanceMethod Here's a REPL demo: 这是一个REPL演示:

user=> (def d (java.util.Date.))
#'user/d
user=> d
#inst "2013-12-04T05:47:33.560-00:00"
user=> (clojure.lang.Reflector/invokeInstanceMethod
        d "setDate" (object-array (list 1)))
nil
user=> d
#inst "2013-12-01T05:47:33.560-00:00"

I'd consider everything about the reflector is an implementation detail (tweaks to method signatures might happen occasionally etc.), but this functionality is necessary in Clojure, in one form or another. 我认为反射器的所有内容都是一个实现细节(方法签名可能偶尔会发生调整等),但这种功能在Clojure中是必需的,有某种形式。

It seems like a simple code transformation by looking at the example you have shown, so why not a macro: 通过查看您显示的示例,这似乎是一个简单的代码转换,为什么不是宏:

(defmacro assoc-obj [obj & props]
  (let [psets (map (fn [[p v]] (list (symbol (str ".set" p)) v ))
                   (partition 2 props))]
    `(doto ~obj ~@psets)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过反射在Java中调用setter方法 - how to invoke setter method by reflection in java 如何在main方法中调用setter方法? - How can I invoke a setter method in the main method? 如何模拟调用集合方法而该集合没有设置方法的方法? - how to mock method which invoke collection method and this collection has not setter? 在UIInput组件中使用带有参数的方法时,如何调用setter方法? - How to invoke setter method when using methods with arguments in UIInput components? 如何在其他任何类构造函数被调用之前调用Spring setter方法? - How to invoke Spring setter method before any other class constructor get invoke? 如何使用 setter 和 getter 方法获取 object 的 object 数组及其响应 - How to get array of object of object and their response using setter and getter method 如何为BSTR *调用OleAutomation对象方法? - How to invoke an OleAutomation Object method for BSTR*? 如何使用反射 API 调用 Setter 方法但没有提到像 FieldName 和 MethodName 这样的东西 - How To Invoke Setter Method using Reflection API But does not mention anything like FieldName & MethodName 我怎样才能在对象变量中实现setter方法? 请解释 - how can i achieve setter method in the object variable?? please explain 带有对象列表的调用方法 - Invoke method with an Object List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM