Want this course?
Creating Java interfaces with gen-interface
Course: JVM Fundamentals for Clojure
Clojure comes with a tool called
gen-interface for building Java interfaces without writing any Java. We look at how to make a new interface including defining its methods.
Hello. We're gonna be talking about gen-interface. Gen Interface is kinda like Gen Class, except instead of creating a class, it creates a JAVA interface and it's way simpler because interfaces are simpler. And one thing that probably needs to be mentioned is that closure runs on an older version of java.
It's compatible all the way back I think to 1.6 which was a long time ago when that came out. In java 1.8, some new stuff came out, like default implementations for methods and interfaces and closure does not support that. But it does support the interface that came before that, which was simply a list of methods with their signatures. So, to create an interface, I've got this file called interface.clj, I mean it's really easy.
We'll start with the interface, gen-interface. There, it's making an interface. Of course the name is number-cruncher.interface. You'll probably want to change that, so we do com.lispcast.MyInterface, so that's the name. You can give it a list of other interfaces it extends, so let's say it will be an iterable and it'll also be a runnable, whatever that means. Then you can add new methods and it has the same formats.
It's a list, different methods. You give it the name of the method, let's say go is the name of the method, and then a list of parameter types. It's gonna take an int. See I can use a lowercase int if it's the same as a java type. It's gonna take an int, it's gonna take a java.util.collection, then what's the return type, it's going to be void. I can specify multiple methods here. And that's it. That's all the options that gen interface has. It'll generate an interface that you can extend from java, so there ya go.