How to generate static methods using clojure class of Gen?

In My Clojure code, I would like to generate a class file containing a static method (called staticMethod ), which is later called 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 #^{:static true} , the Java compiler always says:

It is not possible to make a static reference to the non-static method staticMethod (String, String) of type TestGenClass

How to define static methods in Clojure? Does #^{:static true} and ^:static the same thing? Where is this documented?

+5
source share
1 answer

When kotka said to annotate a method declaration, it "obviosly" meant the entire vector containing the declaration:

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

This type of concise wording is, unfortunately, typical of Clojure documentation.

+9
source

Source: https://habr.com/ru/post/1204922/


All Articles