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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With