jeudi 8 novembre 2018

Clojure, reflection: Find classes that implement an interface

This seems to be a more difficult in Clojure than in Java and Scala. What I want to do is:

  1. Define an interface in Java
  2. Implement it in a class in Clojure (Bonus: with a macro)
  3. Find it using the classloader and reflection

This is what I have so far:

The Java interface

package hello.interfaces;
public interface Test {
    String doSomething(String input);
}

The Clojure definition

(ns hello.impl.test
  (:gen-class
    :implements [hello.interfaces.Test]))

(defn doSomething [v] (str "hello " v))

Searching for the classes:

(ns hello.core
  (:import
    (org.reflections Reflections)
    (org.reflections.util ConfigurationBuilder))
  (:gen-class))

(defn -instances []
  (let [paths (into-array Object ["hello"])]
      (.getSubTypesOf (Reflections. paths) hello.interfaces.Test)))

(defn -main [& args]
  (println (-instances)))

I am using org.reflections. This works if I search for classes that are in the classpath (e.g. in the org.reflections jar) but it does not work for my previously defined class, therefore I think that the problem is not in the last snippet of code but in the previous one, or maybe in the usage, e.g. it requires pre-compiling it.

How can I define classes in Clojure that I can find later with reflection?





Aucun commentaire:

Enregistrer un commentaire