How can I easily write a REPL app in Java?

扶醉桌前 提交于 2019-12-08 00:50:01

问题


I have a CMS server that provides a client library. I'd like to be able to drive the CMS interactively from the command line.

The basic approach would be:

  1. Create a connection to the CMS
  2. Add the CMS connection object to the REPL context
  3. Connect the REPL to stdout/stderr/stdin
  4. Kick off a daemon thread for to keep the REPL running.

I was hoping that I could perhaps leverage Groovy to do this but haven't managed to get it working.

Is there a library that provides REPL support?
Can you provide a simple example?


回答1:


If you don't mind using Scala as your language, you can use the Scala REPL to explore java libraries. You can do this in a number of ways, either with

$ scala -classpath yourjarfileshere.jar

or if you're using maven:

mvn scala:console

If all you're doing is playing (not scripting or anything), then this is a possible way to go.

If you wish to embed your repl, and you're still willing to use Scala, you can look at the answer to these questions: Drop into interpreter during arbitrary scala code location and Launch Scala REPL programatically?

Groovy also has a repl, groovysh, which you can use to explore.




回答2:


Wikipedia page for REPL mentions BeanShell. Would that work?




回答3:


I got this working with Groovy.

Example

public static void main(final String[] args) {

    Binding binding = new Binding();
    // Configure your bindings here.

    Groovysh shell = new Groovysh(binding, new IO());
    shell.run(args);
}

Known Issues

However, it won't work when the app is started from Eclipse (ie using the Eclipse 'console' view). To work around this you must update the Eclipse launch configuration to pass the following VM argument:
-Djline.terminal=jline.UnsupportedTerminal.

More information

  • Documentation of the Groovy Shell.



回答4:


Beanshell can be run as repl in your own thread/main within your application:

public static void main(String[] args) throws Exception{

    Reader inreader = new InputStreamReader(System.in);
    Interpreter i = new Interpreter(inreader, System.out, System.err, true);
    try {
        BufferedReader in = new BufferedReader(inreader);
        String str;
        while ((str = in.readLine()) != null) {
            i.eval(str);
        }
        in.close();
    } catch (Exception e) {
    }
}

that example runs in eclipse fine, you type at it in the console window of eclipse then it will talk back to you fine.



来源:https://stackoverflow.com/questions/7317071/how-can-i-easily-write-a-repl-app-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!