Java9: REPL environment and programming, java9repl environment programming

Source: Internet
Author: User
Tags mercurial

Java9: REPL environment and programming, java9repl environment programming
Subtitle: beginning to provide a REPL environment in Java 9 -- JShell may change the way programmers use and learn Java.

Recommendation of an online REPL demo environment: Java WEB Console http://www.javarepl.com/console.html

You can try to execute some simple Java code, such:

System.out.println("See See REPL")

System.getProperty("user.name")

2 + 2 * 5

One piece said: Why do programmers seem to be doing nothing all day? Because they are compiling code...

What are the advantages of an interactive console? The translator's experience is that it is too convenient to test strings, regular expressions, and other simple programs.

Maybe you have written Clojure and Scala code, or you have also written programs using LISP. If you have loved them, you must have had a good time with REPL.REPL, All calledread-eval-print-loopIs a shell interface used to read the input content line by line, calculate the value of the input content, and then print the output execution result. This is a friendly instant interaction environment that I like very much!

When REPL is used, interactive code is used and executed immediately after input. The release of Java 9 in 2016 is expected to provide a fully functional REPL Environment named JShell (codenamed Kulla ). This article first briefly introduces Java REPL, and then explores how to use it when writing Java code in the future.

Shenma! Java does not have a REPL environment?

For a stable and extensive language like Java, a repl environment is required! But in fact not all languages Support REPL, such as Java (Before. It can be said that, compared with other languages, Java has a lot of developers and should provide a REPL environment. Java also has a REPL-like environment: Java BeanShell, but this project has never been fully functional and only supports some Java syntax.

REPL can reduce the shift time

Shorten the mindset shift time, even if feedback is important to the health of programmers. For programmers who want this feature, REPL is a very powerful tool. In general, it is the most efficient programming method for human brains to immediately see the execution results. With the Java REPL environment, developers can write, execute, and continue writing. No longer need to interrupt your thinking. Compile, package, execute, and then, strange, where did you think?

Although many programs and systems written in Java are far beyond the scope of the interactive command line environment, if a REPL is built in JDK, so we can easily use it at any time. Of course, the usage frequency should be very high. In fact, JShell will also open APIs so that the IDE environment can easily integrate them. Of course, most IDE support is required, and developers also need to use the latest IDE!

Start using JShell

At the time of writing this article, JDK 9 Developer preview bundle does not contain the Kulla project because REPL is still in the development stage. So you need to clone the project source code in Mercurial, compile JDK, and compile JShell by yourself.

This process may take several hours, especially if you are not familiar with the JDK source code. You must disable the warning option as an error. For OSX compilation, make sure that XCode and XQuartz freetype libraries are installed. Follow the steps below to install and run the Kulla project.

1. install Java 9

To use JShell, You need to download and install the latest Java 9 Developer Preview version. After installation, you need to set Environment VariablesJAVA_HOMEThen, you can executejava - versionTo check whether the configuration is correct. There are some pitfalls in the middle, especially on the OSX system, so please remind me!

2. Install Kulla Mercurial and the Project

Kulla is an OpenJDK project that uses the distributed version control system Mercurial. Therefore, you need to clone the Mercurial repository and compile it.

Next we will clone the Kulla Library:

hg clone http://hg.openjdk.java.net/kulla/dev/kulla

Then configure the compilation environment:

cd kullabash ./configure --disable-warnings-as-errorsmake images
3. Compile and run REPL

The following is a command to compile REPL:

cd langtools/replbash ./scripts/compile.sh

Start with the following script:

bash ./scripts/run.sh 

As mentioned above, the REPL function of Java has not been available to normal users yet, but we programmers can play it first!

Perform mathematical operations

What can JShell do? Let's start with a simple mathematical operation.java.lang.MathLibrary:

Listing 1Use REPL to calculate mathematical expressions

$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help-> Math.sqrt( 144.0f );|  Expression value is: 12.0|    assigned to temporary variable $1 of type double-> $1 + 100;|  Expression value is: 112.0|    assigned to temporary variable $2 of type double-> /vars|    double $1 = 12.0|    double $2 = 112.0-> double val = Math.sqrt( 9000 );|  Added variable val of type double with initial value 94.86832980505137

Here we calculate the square root of a number and add the two numbers together. This is not complicated. We can find that,/varCommand to display the list of variables created in a JShell session. You can also use the dollar sign ($) to reference the value of an unassigned expression. Finally, a new variable is created and assigned a value. The Web Console does not support commands starting with this slash]

Definition Method

Next we will do something interesting. In this example, we define a method to calculate the Fibonacci sequence ). After defining the method, we can use/methodsCommand to view the methods defined in the session. Finally, the Code calls the function to print the sequence of the numbers.

Listing 2Calculate the Fibonacci series

$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help-> long fibonacci(long number) {       if ((number == 0) || (number == 1))          return number;       else          return fibonacci(number - 1) + fibonacci(number - 2);    }|  Added method fibonacci(long)-> /methods|    fibonacci (long)long-> fibonacci( 12 )|  Expression value is: 144|    assigned to temporary variable $1 of type long-> int[] array = { 1,2,3,4,5,6,7,8 };|  Added variable array of type int[] with initial value [I@4f4a7090-> for( long i : array ) { System.out.println(fibonacci( i )); }1123581321

In the same JShell window, you can also redefine the Fibonacci method and execute the same code. Because it supports this iterative replacement feature, we can use REPL to quickly execute, modify, and test new algorithms.

Listing 3REPL rewrite Method

-> long fibonacci(long number) {     return 1;   }|  Modified method fibonacci(long)-> for( long i : array ) { System.out.println(fibonacci( i )); }1111111
Definition class

The following code demonstrates how to define a complete class in JShell, and then reference this class in the expression-the entire process is executed in REPL. Here we can dynamically create and test code and test and replace new code.

Listing 4Dynamically define classes

MacOSX:repl tobrien$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help->  class Person {         public String name;         public int age;         public String description;         public Person( String name, int age, String description ) {             this.name = name;             this.age = age;             this.description = description;         }         public String toString() {             return this.name;         }     }|  Added class Person-> Person p1 = new Person( "Tom", 4, "Likes Spiderman" );|  Added variable p1 of type Person with initial value Tom-> /vars|    Person p1 = Tom

Although the dynamic definition class has powerful functions, it does not meet the needs of our developers. After all, it is very rare to write a long and long code in an interactive shell environment. This leadsHistoryWhen you start REPL, you can load the previously saved status. Use/historyCommand to list all statements and expressions that have been executed in REPL.

Listing 5Query historical records/history

-> /historyclass Person {    public String name;    public int age;    public String description;    public Person( String name, int age, String description ) {        this.name = name;        this.age = age;        this.description = description;    }    public String toString() {        return this.name;    }}Person p1 = new Person( "Tom", 4, "Likes Spiderman" );Person p2 = new Person( "Zach", 10, "Good at Math" );/varsp1p2/history

We can also save the REPL history to a file and reload it later. Example:

-> /save output.repl-> /reset|  Resetting state.-> /vars-> /open output.repl-> /vars|    Person p1 = Tom|    Person p2 = Zach

/saveCommand to save the REPL history to the file,/resetCommand to reset the REPL status, while/openCommand to read and execute a file in REPL. By saving and enabling the function, programmers can set complex REPL scripts to configure different REPL scenarios.

Modifying class definitions in the middle

JShell can also set Initialization Configuration Files and automatically load them. You can edit source code entries at will. For example, if you want to modifyPersonClass, you can use the class/listAnd/editCommand.

Listing 6 modifying Person

-> /l   1 : class Person {           public String name;           public int age;           public String description;           public Person( String name, int age, String description ) {               this.name = name;               this.age = age;               this.description = description;           }           public String toString() {               return this.name;           }       }   2 : Person p1 = new Person( "Tom", 4, "Likes Spiderman" );   3 : Person p2 = new Person( "Zach", 10, "Good at Math" );   4 : p1   5 : p2-> /edit 1

Run/editThe command will open a simple Editor, in which you can change the definition of the class, and then the class will be updated immediately.

What is high technology?

If you look at how Clojure or LISP programmers write code, you will find that they primarily develop in the REPL environment. Instead of writing code, compiling and building, like Java, before execution. To be honest, writing a Java program wastes a lot of time for interaction. If you are free, you can talk to Scala or Clojure programmers about REPL to see how they work.

Unlike Scala and Clojure, Java is another language. Java developers do not spend much time focusing on a few common lines of code, while the logic of the LISP program may only be included in a few lines of core code. Most Java programs must be installed first and can run properly after configuration. Although the latest version of the language reduces the number of lines of code to be written, however, we can easily write tens of thousands of lines of code into a complex system using Java. ThePersonClasses are not very useful. The most useful code in Java is often very complicated and hard to be written in a REPL environment.

The Programming environments of Scala and Clojure developers are called "iterative development" by Chas Emerick, author of Clojure Programming, because they do not need to rely on file systems. Java programs depend on many class libraries, which are complex and may depend on containers (such as Tomcat or TomEE ). Therefore, I believe that the REPL-oriented programming method will not replace the traditional IDE programming. However, I think the REPL of Java will be used better in the following areas.

1. Learn Java

Because Java development requires many configurations. For beginners, using REPL can quickly understand the syntax and basic concepts. The REPL of Java 9 will become a Quick Start for beginners.

2. Learn and try new class libraries

Java has hundreds of easy-to-use open-source class libraries, such as mathematical operations and datetime libraries. In the days when there is no REPL, a bunch of "public static void main" must be written each time before testing. However, if you have a command line interaction environment, you only need to enter the key code to see the execution result.

3. Quick prototyping

This is similar to Clojure and Scala development. If you need to focus on solving a problem, you can use REPL to easily iterate and modify classes and algorithms. You can quickly adjust the definition of a class, reset REPL, and try again without waiting for compilation to complete. [Such as regular expression matching and string truncation]

4. Integration with build tools

Gradle provides an interactive "shell" mode, and the Maven community has released similar tools. We can use REPL to reduce the complexity of building and control the running of other systems.

Future

In my opinion, with the popularity of Java 9 in the next few years, REPL will increasingly influence our development and programming methods. Of course, the Java Community also needs time to gradually adapt to new development methods and sum up and bridge the beauty and traps in REPL.

I don't think most Java programmers often use REPL for development, but new programmers will gradually get used to the REPL environment as a way for them to learn Java. With the new Java programmers and REPL having a good time, there is no doubt that it will change the pattern for us to build and develop Java programs.

References:

Original article: What REPL means for Java

Original Article Date: January 1, August 13, 2015

Translated on: February 1, September 16, 2015

Iron anchor http://blog.csdn.net/renfufei

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.