Question

Is there something like python's interactive REPL mode, but for Java? So that I can, for example, type InetAddress.getAllByName( localHostName ) in a window, and immediately get results, without all this public static void nightmare() thing?

Was it helpful?

Solution

edit Since Java 9 there's JShell

Original answer follows

You can also use Groovy Console. It is an interactive console where you can do what you want. Since Groovy also includes classes from the core java platform, you'll be able to use those classes as well.

It looks like this:

Screenshot of Groovy

OTHER TIPS

Eclipse has a feature to do this, although it's not a loop. It's called a "Scrapbook Page". I assume the analogy is supposed to be that you have a scrapbook where you collect little snippets of code.

Anyway, to make it work, open a project in Eclipse (your Scrapbook Page is going to be associated with a project -- Eclipse likes it when projects own things).

Then:

  1. In the project navigator window, select a folder that exists somewhere in your project.
  2. Either select the menu File -> New -> Other, or hit Control-N.
  3. Select Java -> Java Run/Debug -> Scrapbook Page.
  4. Hit "Next", then give it a filename, then hit "Finish".

Now you have a scrapbook page. Type some code, like maybe this:

System.out.println(System.getProperties());

Then select the text with the mouse, and either hit Control-U or select "Execute" from the context menu. The code will run and the output will appear on the console.

You can also type an expression, select it, and select Display from the context menu. It'll evaluate the expression and print its type. For example, running Display on 1 + 2 will print (int) 3.

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

You can use Eclipse Scrapbook pages.

In Eclipse create a Scrapbook page. In your project, New->Other->Scrapbook page.

In the file, enter some text, select it and hit ctrl-U, and there you go.

To manage your imports, right click in the page and select Set Imports, where you can choose to import a package or a single class. This is persistent, and is saved with the page.

Old question, but there is a better answer now (May 2013) - java-REPL! It's available on github and also available live at the java-repl website for quick one-off testing.

If you grab the git hub code and run ant to generate the artifacts, you can make it easy to use with a small script like:

#!/bin/sh
java -jar /home/rdahlgren/scripts/javarepl-dev.build.jar

Since finding this project I probably use it 5 times a day. Enjoy!

Seems nobody mentioned yet that Java (6, 7) ships a REPL console called jrunscript. It is language agnostic (so can be used with Jython, JRuby etc.). It defaults to JavaScript (Rhino) which is also bundled by default, and like the other languages you can access all the packages/objects available on the classpath.

As an alternative to Groovy, try Beanshell: http://www.beanshell.org/

It is more Java-like and allows you to use Java-syntax directly.

Jython is a python implementation which lets you inspect and interact with Java objects.

>>> from java.net import *
>>> InetAddress.getAllByName("google.com")
array(java.net.InetAddress,[google.com/209.85.171.100, 
                            google.com/74.125.45.100,
                            google.com/74.125.67.100])

It's part of OpenJDK 9!

A REPL called JShell (developed by Oracle) has been released as part of JDK 9.

Just download JDK 9, and launch bin/jshell.

Screen shot of JShell

Resources

Java-REPL by Albert Latacz works well.

You can try it directly from your browser here: http://www.javarepl.com/term.html

The source code is available here, and it has a decent Intelli-J plugin.

https://github.com/albertlatacz/java-repl

Clojure provides a REPL you can use.

The groovy console allows you to do that. It actually was meant to try and test groovy code, but since groovy is a superset of Java, it allows plain Java stuff as well.

I just entered this into the console:

InetAddress.getAllByName('localhost')

and hit CTRL-R, then it returned:

groovy> InetAddress.getAllByName('localhost')

Result: [localhost/127.0.0.1]

Scala also offers an interactive console. I was able to use it to get a result for the expression in your question by fully qualifying InetAddress, as in:

java.net.InetAddress.getAllByName("localhost")

While JRuby, BeanShell, Julian Fleischer's REPL are there Albert Latacz's REPL seems to be the latest and active.

Tried it with a simple class definition, works fine.

$ java -jar javarepl.jar
Welcome to JavaREPL version 56 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_17)
Type in expression to evaluate.
Type :help for more options.

java> public class Test {
    | public static void execute(String [] s) {
    |  System.out.println(54353 + s[0]);
    | }}

java> Test.execute(new String [] {"234343"});
54353234343

java> System.exit(0);

For folks with access to Mathematica, JLink lets you access Java and script with Mathematica code:

Needs["JLink`"]
LoadJavaClass["java.net.InetAddress"]
InetAddress`getAllByName["localhost"]

Hit Shift-Enter to evaluate, and you get

{<<JavaObject[java.net.Inet4Address>>}

Then you can use Mathematica's Map function to call toString on the returned objects:

#@toString[]& /@ %

to get the result (or to use the less obscure syntax, Map[Function[obj, obj@toString[]], %]):

{"localhost/127.0.0.1"}

If you start to get serious with this, you'll want to read Todd Gayley's tutorial at http://reference.wolfram.com/mathematica/JLink/tutorial/Overview.html.

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.

Most IDE's have a window called something like "immediate mode" that will allow you to evaluate java code on the fly.

You could take a look at BlueJ which is an interactive Java development environment meant for teaching OOP rather than as full IDE like Eclipse or NetBeans. It's kind of fun to have a play with anyway.

You can see it in action on YouTube in a series of Java tutorials.

DrJava is an educational IDE that includes an REPL pane.

There is an Eclipse plugin as well, but it hasn't worked for me. I think it just hasn't been updated in a while. So what I generally do is keep a DrJava window open for the "what happens if I do this" questions.

EclipseShell might be good too, but I haven't used it yet.

There is simple IDE called DrJava that has an Interactions console. It works exactly as I would expect. Just load a file and start interacting with the objects in it.

There's an online REPL: http://www.javarepl.com/console.html

Typing more to reach the character limit ...

For java 8, there is nudge4j. see https://github.com/lorenzoongithub/nudge4j

nudge4j java repl

... and the beauty is that you can pilot your application from the browsert

JPad is a java scratchpad with a builtin REPL:

C:\>jpad
       _ _____          _
      | |  __ \        | |
      | | |__) |_ _  __| |
  _   | |  ___/ _` |/ _` |
 | |__| | |  | (_| | (_| |
  \____/|_|   \__,_|\__,_|



Anything you type is evaluated as java.
The code is continuously appended until you call \clear.
Other Available Commands:
\exit - exit
\clear (n) - clear past java statements
\history - display all past java statements
\help - display this help

j>2+2
4
j>Math.sin(100.1)
-0.4177477
j>

It is also smart about dumping collections, lists, maps etc and allows rendering them as a table or chart:

enter image description here

Java 9 is providing the JShell.

jshell> println( "Print me!")
jshell> Print me!

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top