【问题标题】:How can I pass in the list of methods to gen-class?如何将方法列表传递给 gen-class?
【发布时间】:2013-04-24 18:11:47
【问题描述】:

当使用gen-class 时编译正常:

(ns clj.sandbox)

(defn -hello
  [this]
  "Hello World")

(gen-class
  :name com.sandbox.GeneratedClass
  :methods [[hello [] String]])

但如果你这样做:

(ns clj.sandbox)

(def my-methods (atom [[hello [] String]]))

(defn -hello
  [this]
  "Hello World")

(gen-class
  :name com.sandbox.GeneratedClass
  :methods @my-methods)

你得到这个错误:

CompilerException java.lang.RuntimeException: Unable to resolve symbol: hello in this context, 正在编译:(clj\sandbox.clj:3:17)

有什么办法可以绕过这个错误吗?我希望能够传入 :methods 值而不是内联定义它。


如果重要的话,这是我用来生成这个的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    
    <artifactId>sandbox</artifactId>
    <groupId>com.sandbox</groupId>
    <version>1.0-SNAPSHOT</version>    
    <packaging>clojure</packaging>
    <modelVersion>4.0.0</modelVersion>    
    <build>        
        <plugins>
            <plugin>
                <groupId>com.theoryinpractise</groupId>
                <artifactId>clojure-maven-plugin</artifactId>
                <version>1.3.13</version>
                <extensions>true</extensions>
                <configuration>
                  <sourceDirectories>
                    <sourceDirectory>src</sourceDirectory>
                  </sourceDirectories>
                </configuration>
            </plugin>
        </plugins>        
    </build>
    <dependencies>        
        <dependency>
            <groupId>org.clojure</groupId>
            <artifactId>clojure</artifactId>
            <version>1.5.1</version>
        </dependency>
    </dependencies>
</project>

【问题讨论】:

  • 我把hello函数后面的“-”去掉了,这样就有了(defn hello [this] ...),没有报错。
  • @dizzystar 是的,它会运行,但它无法生成类,因为它无法找到实现。
  • 也许看看多方法。 clojure.org/multimethods,备忘单总是救命稻草:clojure.org/cheatsheet。希望对您有所帮助,但我不完全确定您要完成什么。
  • @dizzystar 我看不出多方法与此有什么关系
  • 不要让像@amalloy 这样脾气暴躁的老人毁了你的梦想。 :-) 如果你成功了,结果可能不是你真正想要使用的任何东西,但到达那里的旅程无疑会很有启发性。您将需要编写一个宏,无疑是一个相当复杂的宏。我建议写出您想要生成的那种复杂的 gen-class 形式,以及应该生成它的等效宏调用。最后,编写从一个转换为另一个的普通函数和一个小宏来调用这些函数。或者找一些更实际的事情来处理你的时间。 :-) 不管怎样,祝你好运!

标签: clojure gen-class


【解决方案1】:

因为 gen-class 是一个宏并且将 @my-methods 传递给它会导致宏获取 (deref my-method) 作为方法参数的值,这不是预期的。您需要创建一个包装宏,然后调用它,如下所示:

(defn -hello []
  "Hello world")

(def my-methods (atom '[[hello [] String]]))

(defmacro my-class []
  `(gen-class
    :name com.sandbox.GeneratedClass
    :methods ~(deref my-methods)))

(my-class)

另请注意,引用原子值,否则您将收到 hello not found 异常,因为它会尝试解析不存在的 hello var。

【讨论】:

  • 好的,非常感谢您的回复。我会尽快尝试的。出于好奇,我怎么能自己调试呢?我尝试运行macroexpand-1,但它只返回nil
  • gen-class 宏不发出任何代码,它只是执行一些创建类文件并返回 nil 的代码
猜你喜欢
  • 1970-01-01
  • 2014-12-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 2020-11-14
  • 1970-01-01
相关资源
最近更新 更多