简体   繁体   中英

How can I proxy a Java class with overloaded methods in Clojure?

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

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 .

(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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM