给Clojure gen-class附加元数据

6

是否可以将元数据附加到Clojure的gen-class?

我正在尝试实现一个使用需要在类中添加Java注释的库的服务器。

根据Chas Emerick等人即将出版的书《Programming Clojure》(第9.7.3节),向gen-class方法添加注释很容易,但没有提及如何添加类级别的注释。

3个回答

24

是的,我在这里找到了一个很好的例子:

https://github.com/clojure/clojure/blob/master/test/clojure/test_clojure/genclass/examples.clj

以下是内联代码,以便在未来不会消失:

(gen-class :name ^{Deprecated {}
                   SuppressWarnings ["Warning1"] ; discarded
                   java.lang.annotation.Target []}
                 clojure.test_clojure.genclass.examples.ExampleAnnotationClass
           :prefix "annot-"
           :methods [[^{Deprecated {}
                        Override {}} ;discarded
                      foo [^{java.lang.annotation.Retention java.lang.annotation.RetentionPolicy/SOURCE
                             java.lang.annotation.Target    [java.lang.annotation.ElementType/TYPE
                                                             java.lang.annotation.ElementType/PARAMETER]}
                           String] void]])

1

我认为目前这是不可能的。

Rich Hickey在这个帖子https://groups.google.com/group/clojure/browse_thread/thread/d2128e1505c0c117中提到了添加注释支持,但据我所知,这仅适用于deftype / defrecord。当然我可能是错的。

这两个

(ns genclass.example
  (:gen-class ^{:doc "example class"}))

(ns genclass.example)

(with-meta
  (gen-class
   :name genclass.example.ClassA
   :methods [[hello [] void]])
  {:doc "Example class"})      

编译失败了。来自异常信息

Exception in thread "main" java.lang.IllegalArgumentException: Metadata can only be applied to IMetas (example.clj:4)`

听起来似乎不可能。


1
我已经开始在我的JAX-RS REST服务器中使用deftype而不是gen-class,遵循Chas书中的示例。它看起来更"简洁"。 - Ralph
你可能还会喜欢Chas制作的以下流程图:http://cemerick.com/2011/07/05/flowchart-for-choosing-the-right-clojure-type-definition-form/ 这可能是在他的书中,我还没有看过... - Paul
我在 Twitter 上第一次看到了这个流程图。非常不错!谢谢。 - Ralph
@Ralph,你能否好心将另一个答案标记为被接受的答案?因为现在可以通过gen-class附加注释。 - Jakub Holý

1
为了补充一些信息,因为我在其他地方找不到记录,也可以向构造函数添加注释。
您可以通过向构造函数对的第一个数组中添加元数据来向构造函数添加注释。像这样:
(gen-class
  :name "FooClass"
  :init "init"
  :constructors {^{Inject {}} [Configuration] []}
  :state "state"
  :implements [FooInterface]
  :prefix "ref-")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接