How can I easily write a REPL app in Java?

情到浓时终转凉″ 提交于 2019-12-06 09:00:20
Matthew Farwell

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.

Wikipedia page for REPL mentions BeanShell. Would that work?

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

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.

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