簡體   English   中英

如何將方法列表傳遞給gen-class?

[英]How can I pass in the list of methods to gen-class?

使用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:無法解析符號:在這種情況下,您好,編譯:(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>

因為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)

還要注意,atom值被引用了,否則您將得到hello not found異常,因為它試圖解析hello var不在其中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM