Can you extend a Java class, and add new fields and constructors to it?

214 views
Skip to first unread message

Didier

unread,
Mar 23, 2017, 2:12:36 AM3/23/17
to Clojure
Hi,

I'm trying to see if you can extend a Java class in Clojure, in a way that lets you add class members (fields) and new constructor methods.

I'm pretty sure you can not with reify, since that only works on interfaces and protocol, but I'm thinking there should be a way to do so with proxy maybe?

Thanks.

Erik Assum

unread,
Mar 23, 2017, 2:30:35 AM3/23/17
to clo...@googlegroups.com
Not sure that this is exactly what you're asking for, but it might still give you a starting point:

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mars0i

unread,
Mar 23, 2017, 8:32:50 PM3/23/17
to Clojure
gen-class lets you define multiple constructors: http://stackoverflow.com/questions/18780071/clojure-multiple-constructors-using-gen-class

You can't define multiple fields that can be directed accessed from Java, but you can define accessors for data you store in other ways. gen-class gives you only a single variable that's specific to each instance of the class, but you can e.g. put a map in it, with atoms as values if you need mutability, and define the accessors to access those.

(If you have a lot of variables that you're handling that way, you may want to write a gen-class-generating macro. That's what I did, but it's not general; it's tailored to my application.)

Reply all
Reply to author
Forward
0 new messages