使用Clojure中的Java注解

huangapple go评论66阅读模式
英文:

Use java annotations in clojure

问题

(.b a (proxy [C] []
  (^{Handler {}} ; 在这里添加 Java 注解
    d [] (println "hello world"))))

请注意,上面的 Clojure 代码中,我已经在 ^{:Handler {}} 部分添加了 Java 注解。这是您在 Clojure 中向方法添加 Java 注解的正确方式。如果您仍然遇到问题,可能是其他方面的代码逻辑或环境设置导致的。

英文:
a.b(new C() {
  @Handler
  public void d() {
    System.out.println("hello world");
  }
});

I tried to translated it to clojure:

(.b a (proxy [C] []
  (^{Handler {}}
    d [] (println "hello world"))))

But unfortunately it doesn't work.

Is this correct? How should I add java annotation to a method?

答案1

得分: 2

我一般建议您将您的互操作代码编写在Java中:提供一个符合Java需求的API,并通过调用您的Clojure函数来实现它。Clojure转换为Java的层次结构并不丰富,无法创建除reifydefrecord之外的类型,我发现要处理注解或扩展类等复杂操作会很麻烦。

英文:

I generally suggest writing your interop code in Java: present an API that fits what Java wants, and implement it with calls to your Clojure functions. The Clojure->Java translation layer is just not that rich for creating types that are not just reify or defrecord, and I find it a big burden to do anything fancy, like handle annotations, or extend classes.

答案2

得分: 1

这里有相关文档链接

基于此,我会尝试类似以下方式:

(deftype ^{Handler true} CC [] ...)
(.b a (CC.))

文档中没有提到代理(proxy)/reify的支持,所以我正在显式地创建一个新类。

英文:

There's documentation for this here

Based on that I'd try something along the lines of

(deftype ^{Handler true} CC [] ...)
(.b a (CC.))

There's no mention of proxy/reify support, that's why I'm creating a new class explicitly.

huangapple
  • 本文由 发表于 2020年9月2日 18:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63703970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定