Reputation: 14258
Is there a way of using reflection to create a class programmatically? For instance. Is there a private constructor we can use to create a class type that then can be used to create instances of that class?
I know that there are other tricks like generating source code and compiling it, or generating byte code and loading it using a classloader... But I want to see if it is possible to somehow create an instance of java.lang.Class directly.
I want to write the following code in clojure:
(def c (create-class "com.example.Dog" {:fields {"legs" 4}
:methods {"bark" (... do something ...)}
:constructors {.....}}))
(def d1 (.newInstance c))
(def d2 (.newInstance c))
Upvotes: 1
Views: 353
Reputation: 91607
Clojure has several ways to generate classes depending on your needs: They are described in the Clojure types page Though I found the chapter on types in Clojure Programming most helpful as a comparison of the various ways of generating classes dynamically.
Under the hood these generate bytecode and load it using a classloader (except for gen-class) which writes class files. There is a lot more to the subject than I can cover here, it's well worth checking out the chapter in Clojure Programming (or your favorite Clojure Book)
Upvotes: 4