13

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
2
  • I don't have an answer, but your question spurred me to read "proxy_core.clj" which made me slightly smarter, so thanks! :) Commented May 19, 2011 at 12:17
  • I actually did the same. If anyone else is interested proxy_core.clj is here. Commented May 19, 2011 at 14:11

1 Answer 1

4

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)))
Sign up to request clarification or add additional context in comments.

2 Comments

I actually tried exactly this but was getting AbstractMethodError and other weird stuff (the real instance where I'm doing this is far more complicated of course). I'll have to try it again. Thanks!
@alex-miller And you must be careful in case the Integer bar calls the back into the String bar. This won't work also with this approach. But @jonathan-tran is right: this is the only way to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.