Is there something like python's interactive REPL mode, but for Java?

Viewed 22976

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?

29 Answers

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

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])

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

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

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")

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.

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

Since JDK 11, which was released in September 2018, the java command allows launching of a single java source code file. See bug report 8192920 and also JEP 330

Related