Using Lisp or Scheme for runtime configuration of Java programs

后端 未结 4 1321
梦毁少年i
梦毁少年i 2021-02-05 22:59

I have now seen several projects ending at a point where the actual configuration depended on things only available at run-time.

The typical way to configure a Java prog

4条回答
  •  逝去的感伤
    2021-02-05 23:46

    Good, much smaller solution is an embedded Scheme for Java. Out of many implementations, I found and tested JScheme. (API looks okay: http://jscheme.sourceforge.net/jscheme/doc/api/index.html)

    A simple main program in Java:

    import jscheme.JScheme;
    import jscheme.SchemeException;
    import java.io.*;
    public class SchemeTest {
        public static void main(String[] args) {
            JScheme js = null;
            try {
                js = new JScheme();
                js.load(new FileReader("config.scm"));
            } catch (FileNotFoundException e) { return; }
    
            System.out.println("Message: '" + js.eval("msg") + "'");
    
            // Values
            int answer = (Integer) js.eval("answer");
    
            // Function calls
            System.out.println(js.call("countdown", 42));
        }
    }
    

    And an example config.scm:

    (define (countdown x)
      (define (loop x acc)
        (if (= x 0)
          acc
          (loop (- x 1) (+ acc x))))
      (loop x 0))
    
    ;;; config variables
    (define msg "Hello from JScheme!")
    ;; tail calls are optimized as required
    (define answer (countdown 42))
    

    The scheme is being interpreted at startup every time, so this is good choice for configurations. Advantages to JScheme include:

    • good JVM integration
    • apparently a complete Scheme implementation
    • smallish size (572 kB)
    • fast, somewhat easily called from Java

    Benchmark update: this code runs in 0.13 seconds time. Compared to the Clojure version's time this is pretty fast.

提交回复
热议问题