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. Something like this (but this won't work):
我如何在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)))
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
1 个解决方案
#1
3
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)))
#1
3
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)))