---
title: "关于clojure的gen-class"
author: "Aaron5"
date: "2014-05-15T12:04:52Z"
tags: []
categories: ["编程语言"]
slug: "clojure-gen-class"
draft: false
lastmod: "2014-05-15T12:18:06Z"
id: 2066740
url: "https://clojure.iteye.com/blog/2066740"
---

**关于gen-class的参数说明：**

:name aname
要生成的类的全限定名

:extends aclass
指定superclass，没有指定默认为Object

:implements 
要实现的接口

:init name
指定构造函数名称，必须返回 state] 
如果没有指定，则args传给superclass，并且state为nil

:constructors { , ...}
指定构造参数的类型

:post-init name
init之后执行

:methods  return-type], ...]
定义开放的方法，默认为non-private方法，静态方法加^{:static true}。

:main boolean
指定的main方法。名称为(str prefix main)。prefix默认为减号。也可以自己指定prefix。

:factory name
工厂方法

:state name
存放的state的名称，state是ref或者agent类型。（对应于init中的state。必须要配置init）

:exposes {protected-field-name {:get name :set name}, ...}
暴露get，set方法

:exposes-methods {super-method-name exposed-name, ...}
需要暴露哪些方法

:prefix string
前缀，默认为减号。查找方法要以(str prefix fn-name)为准，所以main方法写成-main。可以认为是public的一个标识符。

:impl-ns name
指定实现方法的ns

:load-impl-ns boolean
默认为true，和impl-ns配套使用

**一个例子**

```clojure

(ns com.example )

(gen-class
      :name com.example.Demo
      :state state
      :init init
      :prefix "-"
      :main false
      :methods [[setlocation [string] void]
                [getlocation [] String]])

;;构造函数。state值为：(atom {:location "default"})
(defn -init []
  [[] (atom {:location "default"})])

;;保存字段到state中
(defn setfield
  [this key value]
      (swap! (.state this) into {key value}))

;;从state中获取field
(defn getfield
  [this key]
  (@(.state this) key))

(defn -setLocation [this loc]
  (setfield this :location loc))

(defn  -getLocation
  [this]
  (getfield this :location))

;;main入口，可以在lein中配置:main参数，然后执行lein uberjar来打包一个可执行的jar包。
(defn -main [& args]
  (pritnln "Hello,World!"))

;; 编译后，添加到classpath。当成java类来调用、执行。
user=> (def ex (com.example.Demo.))
#'user/ex
user=> (.getLocation ex)
"default"
user=> (.setLocation ex "time")
nil
user=> (.getLocation ex)
"time"

```