Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate generate static methods with clojure's Gen-class?

In My Clojure-code I'd like to generate a class-file that contains a static method (named staticMethod), which is later on called by in a static context from a Java-program.

I tried (Clojure):

(ns com.stackoverflow.clojure.testGenClass
  (:gen-class
     :name com.stackoverflow.clojure.TestGenClass
     :prefix "java-"
     :methods [
               [#^{:static true} staticMethod [String String] String]
              ]))

(def ^:private pre "START: ")

(defn #^{:static true} java-staticMethod [this text post]
  (str pre text post))

and (Java):

package com.stackoverflow.clojure;

public class TestGenClassTest {

    private TestGenClassTest() {
    }

    public static void main(String[] args) {
        TestGenClass.staticMethod("Static call from Java!", " :END");
    }
}

On https://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html I read:

By adding metadata – via #^{:static true} – to a method declaration you can also define static methods.

No matter where I put the #^{:static true} the Java compiler always says:

Cannot make a static reference to the non-static method staticMethod(String, String) from the type TestGenClass

How can I define static methods in Clojure? Would #^{:static true} and ^:static mean the same? Where is this documented?

like image 876
Edward Avatar asked Oct 17 '14 12:10

Edward


Video Answer


1 Answers

When kotka said to annotate the method declaration, he "obviosly" meant the entire vector holding the declaration:

:methods [^:static [staticMethod [String String] String] ]

This kind of laconic wording is unfortunately typical of Clojure documentation.

like image 93
Marko Topolnik Avatar answered Oct 18 '22 05:10

Marko Topolnik