是否可以从Clojure重新定义Java方法? [英] Is it possible to redefine Java methods from Clojure?

查看:94
本文介绍了是否可以从Clojure重新定义Java方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用多方法,我们可以向现有的Java类中添加方法。我的问题是是否可以重新定义一个特定的方法,以及如何,从Clojure代码。例如,如果你有以下类,

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() {
        ...
    }
}



能够运行一些东西来添加一个before方法,例如:

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

我的目的是这个附件的before / after / around,类似AOP的行为,是在现有实例上调用该方法的框架可以动态更改,并开始运行新附加的代码。目前我使用的是AspectJ的,但我要达到一个点,使用不同的编译器不是一个选项,我很想知道,如果我可以只是沟槽AspectJ。

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.

推荐答案

简单答案:不。

与Java一样,修改类的唯一方法是extend(subclass)它。您可以扩展 Shape 并覆盖 draw 方法(假设 draw 未声明 final )。在Clojure中,这可以通过 proxy gen-class 来完成。

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.

这篇关于是否可以从Clojure重新定义Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆