2

I want to generate a class (not an object) via proxy, and the class will be instantiated later.

The examples I have found of Clojure's proxy method seem to largely deal with the most common java inner class scenario, i.e., when we are only defining a class because we want to create an instance of it.

In my case, I want to define a true class - one which can be loaded later on.. But I'd like to define it without having to compile it using the complexity of gen-class.

Would that be possible at all? Or is gen-class a requirement?

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
jayunit100
  • 17,388
  • 22
  • 92
  • 167

1 Answers1

1

If you define a Clojure Protocol and then create a class that implements that protocol you can then create instances later that are simple classes.

 (defprotocol myProtocol
  (doStuff [this x y])
  (getA [this])
  (setA [this n]))

(deftype Foo [ ^:unsynchronized-mutable a]
  myProtocol
  (doStuff [this x y] (+ x y a))
  (getA [this] a)
  (setA [this n] (set! a n)))

(def a (Foo. 42))

user> (.getA a)
42
user> (.setA a 41)
41
user> (.getA a)
41
user> (.doStuff a 3 4)
48
user> (class a)
user.Foo

The class that gets created goes in a package with the same name as the namespace that called deftype

Community
  • 1
  • 1
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284