在网上找了好久没找到 clojure 入门例子,自己写一个分享一下吧。
eclipse插件:
URL http://ccw.cgrand.net/updatesite
一、clojure 代码:
1 2 3 4 5 6 7 8 9 10
| (require ['com.demo.StringOp])
(ns com.test.Demo (:gen-class :name com.test.Demo :methods [# [getStr [String] String]]) )
(defn -getStr [name](str(com.demo.StringOp/getStr name) " 结束!"))
|
1 2
| (ns com.demo.StringOp) (defn getStr [value] (str "测试字符串:'" value "'"))
|
二、java 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package com.kinsou; import java.io.IOException; import org.junit.Test; import clojure.lang.RT; import clojure.lang.Var; import com.test.Demo; import static org.junit.Assert.*;
public class Main {
private static String getStrTest1(String value) { Object obj = Demo.getStr(value); System.out.println(obj); return obj.toString(); }
private static String getStrTest2(String value) throws IOException { RT.loadResourceScript("com/test/Demo.clj"); Var var = RT.var("com.test.Demo", "-getStr"); Object obj = var.invoke(value); System.out.println(obj); return obj.toString(); } @Test public void test() throws IOException { String value1="测试1"; assertEquals(getStrTest1(value1),"测试字符串:'"+value1+"' 结束!"); String value2="测试2"; assertEquals(getStrTest2(value2),"测试字符串:'"+value2+"' 结束!"); } }
|