制作一个类,该类扩展了Clojure中的重写类 [英] Make a class that extends a class with overriding in clojure

查看:70
本文介绍了制作一个类,该类扩展了Clojure中的重写类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有非常简单的Java代码:

I've got pretty simple java code:

public class MessageListenerExample extends ListenerAdapter
{
    @Override
    public void onMessageReceived(MessageReceivedEvent event)
    {
        // do something with event
    }
}

但是,我似乎无法理解如何将该代码转换为clojure代码.文档和文章非常混乱.我也很高兴看到更多示例.我也对使用implements感兴趣.

However, I can't seem to understand how to turn that code into clojure code. The docs and articles are very confusing. I'd be happy to see more examples too. I'm also interested in using implements.

推荐答案

根据您需要执行的操作,有几种选择:

Depending on what you need to do, a few options:

  1. 如果您确实需要在Clojure中扩展一个类(而不是Object),则可以使用gen-class来实现,请参见
  1. If you really need to extend a class (other than Object) in Clojure, then you can do it using gen-class, see https://clojuredocs.org/clojure.core/gen-class. Preferably using ns macro, like

(ns your.class.Name
    :extends whatever.needs.to.be.Extended)

(defn -methodYouOverride   ; mind the dash - it's important
    [...] ...)

除非绝对必要,否则我不建议您沿着这条路走.正确进行编译(包括AOT编译)非常棘手.最后,您仍然需要使用Java interop来处理此类的对象,因此不确定是否值得麻烦,这使我想到了:

I wouldn't recommend going down this path unless absolutely necessary. Getting compilation right (including AOT compilation) is tricky. And in the end you still need to use Java interop to work with the objects of this class, so not sure it's worth the hassle, which brings me to:

  1. 使用Java对其进行编码,并使用Java interop对其进行处理.

  1. Code it in Java and use Java interop to work with it.

如果您实际上需要创建实现某个接口的对象的实例,那么会更容易:

If you actually need to create an instance of an object that implements a certain interface, then it's easier:

(reify
   InterfaceYouImplement
   (methodYouImplement [..] ..)

我在代码中使用它,用Java编写的代码确实要好得多.

I use it around my code, it's really much nicer that coding in Java.

这篇关于制作一个类,该类扩展了Clojure中的重写类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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