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

查看:22
本文介绍了是否可以从 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"))

在评估该表单之后,所有后续的 draw 调用将在执行调用之前开始打印一个字符串.

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

我使用这个类似 AOP 行为的 before/after/around 附件的目的是,在现有实例上调用该方法的框架可以动态更改并开始运行新附加的代码.目前我正在为此使用 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 中一样,修改类的唯一方法是扩展(子类化)它.您可以扩展 Shape 并覆盖 draw 方法(假设 draw 未声明为 final).在 Clojure 中,这可以通过 proxygen-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天全站免登陆