How can a static initializer be defined using gen-class

382 views Asked by At

I am generating a Java class from Clojure that implements a JDBC Driver, the problem is that usually JDBC drivers register themselves with the DriverManager in a static initializer like so:

public class MyDriver implements java.sql.Driver {
    ...
    static { 
        ...
        try {
            DriverManager.registerDriver(new MyDriver());
        } catch (SQLException s) {
            throw (RuntimeException) new RuntimeException
                ("could not register MyDriver driver!").initCause(s);
        }
        ...
     }
}

What do I have to put in the gen-class declaration and which name should the function that implements it have?

Thanks.

1

There are 1 answers

0
sw1nn On

I don't believe this is possible in pure gen-class at present. clojure's gen-class always generates a static initializer where it ties the generated class to the clojure runtime with a call to

clojure.lang.Var#internPrivate(String, String)

There is some flexibility in the generation of that static initializer (see the :load-impl-ns option to gen-class), but there isn't a way to add your own custom code to the initializer that I can see after reviewing genclass.clj.

btw - as a slight aside, in the JVM the name of the static initializer 'method' is <clinit>