Clojure uses gen-class to implement java interface and test in java

Does clojure implement java interface with gen-class and compile it into class file in advance?


This has troubled me for a long time. Although there are examples in "clojure programming", but I don't know how to run these examples. Some details are not mentioned, which makes me separate from the actual operation.

This blog also mentions some examples of gen-class: https://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html

But I still don't know the details of how to make these examples work.

I will use a small example to illustrate the details that I don't understand. It involves the use of lein, a clojure project build tool.

The main idea of ​​this example is to define an interface with java, then use clojure's gen-class to implement the interface, and finally test whether the implementation is successful in java.

The gen-class function is changed to':gen-class' when used in the ns function. This method means that the clojure code will be compiled into java class files in advance.

Then java calls the method in the class file.


1. Create a clojure project managed by lein, named gen_class: lein new gen_class
then enter the project root directory and modify the project.clj file to:
(defproject gen_class "0.1.0-SNAPSHOT"
	:description "FIXME: write description"
	:url "http://example.com/FIXME"
	:license {:name "Eclipse Public License"
		  :url "http://www.eclipse.org/legal/epl-v10.html"}
	:dependencies [[org.clojure/clojure "1.7.0"]]
	:aot [gen-class.HelloImpl]
	:java-source-paths ["src/java_source"])
 #:aot means to compile the file gen-class.HelloImpl.clj in advance

 #:java-source-paths means that the java code path is specified, and the code under this path will be automatically compiled before clojure code is compiled.

2. Enter the project directory: src/gen_class
cd gen_class/src/
Create a folder: java_source/java_source
Create a file HelloInterface.java that defines the java interface
package java_source;
public interface HelloInterface {
	void sayHello();
}
3. Create the clojure file HelloImpl.clj under the path src/gen-class:
(ns gen-class.HelloImpl
	(:gen-class
	:implements [java_source.HelloInterface]))

(defn -sayHello
     [this ^String para]
(println "Hello, world! " para))
4. Open cmd in the project root directory and execute the command: lein compile
5. HelloInterface and HelloImpl will be compiled into class files in the target directory.
6. Enter the test/gen-class directory, create a java directory, write the test java file Test.java, and call the sayHello method in HelloImpl.class in it.
package gen_class.java;

import gen_class.HelloImpl;
import java_source.HelloInterface;

public class Test {
	public static void main(String[] args) {
		HelloInterface HelloI = new HelloImpl();
		HelloI.sayHello("Java");
	} 
}

Guess you like

Origin blog.csdn.net/lx1848/article/details/51605147