Interactive interpreter for Java
Is there a good interactive interpreter for Java, similar to Scala's? When programming, I like to try small pieces of code to see if they work like I expect before plugging them in to my main program. I would prefer an interpreter that is not based online since I often work offl开发者_StackOverflowine.
Thanks in advance!
Since Scala runs on a JVM, why not the Scala interpreter? That's what I do when I need to test a few Java-snippets.
It's nice to have tab completion that works.
scala> System.getPropert
getProperties getProperty
scala> System.getProperty("user.home")
res0: String = c:\Users\robert
Ok, you have to know a bit about Scala syntax when you do stuff like:
scala> val testMap = new java.util.HashMap[String, java.util.List[String]]
testMap: java.util.HashMap[String,java.util.List[String]] = {}
scala> testMap.put("planets", java.util.Arrays.asList("Mars", "Jupiter", "Pluto"
))
res0: java.util.List[String] = null
scala> testMap.get("planets")
res1: java.util.List[String] = [Mars, Jupiter, Pluto]
In the past I used beanshell. It was really light and got the job done. http://www.beanshell.org/
You can use Dr. Java. It has an interactions
window that acts like an interpreter. I don't know how they developed it though, so, you better use it cautiously. E.g. if you have a class with a private
method, Dr. Java
's interactions
will let you use this method by instance.
I used BlueJ a bit in college. It was started as a teaching tool, it's perfect for tinkering with code and the project is (was?) supported by Sun so I guess that's a feather in its cap too. It's been a while since I've used it but the nice thing I remember about it is that you can tinker with the code you write without writing a main() class. You can write a class, create an instance, call methods (it will prompt you for parameters) and so on. There's also a visual aspect to it as well, somewhat comparable to the inspector in Eclipse.
http://www.bluej.org/about/what.html
Since Java 9 the JDK comes with it's own REPL, the jshell.
If the java/bin
directory is on the PATH
you should be able to start it from the command line.
$ jshell
| Welcome to JShell -- Version 11.0.14
| For an introduction type: /help intro
jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
jshell> 1 + 1
$1 ==> 2
jshell> int foo(int x) {
...> return x + 1;
...> }
| created method foo(int)
jshell> foo(5)
$3 ==> 6
You can see the current imports by calling /imports
.
Jshell starts with default imports but you can always import more classes as long as they are on the classpath.
You can start the jshell and provide a classpath argument:
$ jshell --class-path /opt/libs/guava-19.0.jar:/opt/libs/commons-lang3-3.4.jar
See more regarding classpath options in this answer.
精彩评论