如何在Clojure中使用重载方法代理Java类?

时间:2011-05-19 03:40:17

标签: java proxy clojure

例如,给定一个Java类:

public class Foo {
  public String bar(String x) {
    return "string " + x;
  }
  public String bar(Integer x) {
    return "integer " + x;
  }
}

如何在Clojure中继承Foo并仅覆盖bar(String)方法,但重用原始Foo类中的bar(Integer)。像这样的东西(但这不起作用):

(let [myFoo (proxy [Foo] [] 
              (bar [^String x] (str "my " x)))]
  (println "with string:  " (.bar myFoo "abc"))
  (println "with integer: " (.bar myFoo 10)))

此示例将打印:

with string:   my abc 
with integer:  my 10

但我希望得到以下效果:

with string:   my abc 
with integer:  integer 10

1 个答案:

答案 0 :(得分:3)

我猜这不是你的意思,但在此期间,你可以明确检查参数的类型,并使用proxy-superFoo上调用原始方法。

(let [myFoo (proxy [Foo] [] 
              (bar [x]
                (if (instance? String x)
                  (str "my " x)
                  (proxy-super bar x))))]
  (println "with string:  " (.bar myFoo "abc"))
  (println "with integer: " (.bar myFoo 10)))