有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Java编写的类是否可以实现用Clojure编写的协议?

我只能找到相反的东西;使用Clojure实现Java接口。然而,我想用Clojure编写一个程序,并允许用Java对其进行扩展。例如:

# P.clj
(defprotocol P
  (f [a])
  (g [a b]))

# I.java
public class I implements P {
    public Object f(Object a) { … }
    public Object g(Object a, Object b) { … }
}

另外,我如何指定参数类型,这样就不必到处使用Object

我目前看到的唯一选择是使用点表示法和依赖duck类型,但我更喜欢在Java端对接口实现进行编译时验证


共 (2) 个答案

  1. # 1 楼答案

    正如以撒已经说过的,是的

    然而,没有源代码表示,我认为这是一种horssh*t声明。请注意,我这么说并不是指艾萨克的回答。我指的是Clojure在本案中的工作方式

    如果您需要Java互操作,您可能希望继续使用无聊的Java接口。我认为这也会使在JVM中与其他语言进行互操作变得更容易,因为它是最不常见的分母。我还认为这使与非Clojure开发者的沟通变得更容易

  2. # 2 楼答案

    是的,这是很有可能的,就像那样

    docs的相关部分:

    defprotocol will automatically generate a corresponding interface, with the same name as the protocol, i.e. given a protocol my.ns/Protocol, an interface my.ns.Protocol. The interface will have methods corresponding to the protocol functions, and the protocol will automatically work with instances of the interface.

    为了回答你的问题:

    A Java client looking to participate in the protocol can do so most efficiently by implementing the protocol-generated interface.