Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to redefine Java methods from Clojure?

Tags:

clojure

aop

Using multimethods we are able to add methods to existing Java classes. My question is whether it is possible to redefine one specific method, and how, from Clojure code. For instance, if you have the following class,

public class Shape {
    public void draw() {
        ...
    }
}

I'd like to be able to run something to add a before method, such as this:

(attach-to-method Shape/draw :before
    (println "... about to draw a shape"))

And after evaluating that form, all subsequent calls to draw would start printing a string before performing the call itself.

My purpose with this attachment of before/after/around, AOP-like behavior, is that a framework calling that method on an existing instance can be dynamically changed and start running the newly-attached code. Currently I'm using AspectJ for that, but I'm getting to a point where using a different compiler isn't an option, and I'm curious to know if I can just ditch AspectJ.

like image 789
Edgar Gonçalves Avatar asked Aug 08 '10 16:08

Edgar Gonçalves


1 Answers

Short answer: No.

As in Java, the only way to modify a class is to extend (subclass) it. You can extend Shape and override the draw method (assuming draw is not declared final). In Clojure, this can be accomplished with proxy or gen-class.

like image 60
Stuart Sierra Avatar answered Nov 28 '22 10:11

Stuart Sierra