如何在 Clojure 中使用重载方法代理 Java 类?
例如,给定一个如下 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
For example, given a Java class like:
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):
(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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜这不是您的意思,但与此同时,您可以显式检查参数的类型并使用
proxy-super
调用Foo
上的原始方法。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 onFoo
.