Overriding a java protected method and calling the super-class method from within

959 views
Skip to first unread message

László Török

unread,
Jan 20, 2011, 7:44:23 AM1/20/11
to clo...@googlegroups.com
Hi,

I am quite new to clojure and in the process of sharpening my skills. I bumped into an interop problem:

I have a Java concrete class A that has a protectedMethod(parameter). I'd like to wrap the method, but also call the one defined in the super class.

I found that (proxy ..) is no good for this, I was trying to figure out gen-class, but seem quite a hassle. Particularly, I don't know how to call the method in the super class i.e. what is the equivalent for super.protectedMethod(..) within the context of gen-class.

Anybody has a clue?

Thanks a lot.

Las

.Bill Smith

unread,
Jan 20, 2011, 8:26:20 AM1/20/11
to clo...@googlegroups.com
There may be others, but one way to do it is to the Java reflection API to call the super class method through its Method object.

Bill

Stuart Sierra

unread,
Jan 21, 2011, 11:35:28 AM1/21/11
to clo...@googlegroups.com
Accessing protected methods is a pain. You could do it with reflection, as Bill said.

In gen-class, you need to add the `:exposes-methods` option to gen-class. This will make the protected method available as a public method, under an alternate name.

For example, if you're extending Java class A which has protectedMethod(parameter), you would have something like:

    (ns com.example.subclass-of-A
      (:gen-class :extends com.example.A
         :exposes-methods {protectedMethod exposedSuperMethod}))
    
    (defn -protectedMethod [this parameter]
      (.exposedSuperMethod this parameter))

-Stuart Sierra
Reply all
Reply to author
Forward
0 new messages