tags:

views:

366

answers:

3
+5  Q: 

Java REPL shell

Hi,

I'm looking for a REPL shell that I can use to test out snippets of Java code. Either a desktop app, or a web app (like the Groovy web console). Ideally, commonly used Java packages like:

java.io.*
java.util.*

should be automatically imported, so that I can copy and paste code from a class without having to add a bunch of imports. Does such a thing exist?

Thanks, Donal

+2  A: 

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript. You can use BeanShell interactively for Java experimentation and debugging as well as to extend your applications in new ways. Scripting Java lends itself to a wide variety of applications including rapid prototyping, user scripting extension, rules engines, configuration, testing, dynamic deployment, embedded systems, and even Java education.

http://www.beanshell.org/

http://www.beanshell.org/manual/syntax.html#Standard_Java_Syntax

Bakkal
There are also Jython and JRuby interactive shells for less verbose syntaxes.
Bakkal
jruby link: http://kenai.com/projects/jruby/pages/CallingJavaFromJRuby
rogerdpack
+1  A: 

If you already know Groovy (which I assume you do, since you mentioned the Groovy Console), then just use groovysh or groovyConsole, which are included in the Groovy distro. If you have custom jars that you want to import, you can either write a batch file that starts up groovysh/groovyConsole with those added to the classpath. You can also do this

this.class.classLoader.rootLoader.addURL(new URL("file:///path to file"))

from within the shell to load other jars.

I used to use Jython several years ago to do just what you're asking. As part of my build script, I generated a custom jython.bat and .py file that included the full classpath for the project I was working on. That way when I started Jython, it would have all the code available, and it would bring up Spring to let me twiddle things in the live system. You can do the same thing with Groovy, JRuby, BeanShell, etc.

Joey Gibson
I know I could use the groovy shell, but Groovy doesn't have exactly the same semantics as Java, and has no type-checking. So it's possible that I could get compile errors, or different runtime behaviour with a piece of Java code that seemed to work in the Groovy shell.
Don
A: 

Jython, JIRB for JRuby, Groovy (groovyconsole et al) and Beanshell are all viable options.

I've used the InteractiveConsole for Jython, it really worked nicely in the app.

gpampara