[英]How can I proxy a Java class with overloaded methods in Clojure?
For example, given a Java class like: 例如,给定一个Java类,如:
public class Foo {
public String bar(String x) {
return "string " + x;
}
public String bar(Integer x) {
return "integer " + x;
}
}
How can I subclass Foo in Clojure and override only the bar(String) method but reuse the bar(Integer) from the original Foo class. 我如何在Clojure中子类化Foo并仅覆盖bar(String)方法,但重用原始Foo类中的bar(Integer)。 Something like this (but this won't work): 像这样的东西(但这不起作用):
(let [myFoo (proxy [Foo] []
(bar [^String x] (str "my " x)))]
(println "with string: " (.bar myFoo "abc"))
(println "with integer: " (.bar myFoo 10)))
This example will print: 这个例子将打印:
with string: my abc
with integer: my 10
but I would like to get the effect of: 但我希望得到以下效果:
with string: my abc
with integer: integer 10
I'm guessing this is not what you meant, but in the meantime, you can explicitly check the type of the argument and use proxy-super
to call the original method on Foo
. 我猜这不是你的意思,但在此期间,你可以显式检查参数的类型,并使用proxy-super
来调用Foo
上的原始方法。
(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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.