问题
I went through a couple of tutorials for JShell and I still do not understand the most important part: why would I even use JShell?
Here what Oracle says:
"You can test individual statements, try out different variations of a method, and experiment with unfamiliar APIs within the JShell session".
Yes, great, but for all those things I can just use an IDE. I do understand, that REPL should make code evaluation faster. However, testing a snippet of code in IDE in a dummy Hello World project with Sysout is for sure not slower?
In fact, IDEs provide autocomplete, detect errors early and I can checkout an implementation of a method/class with a mouse click. This all should make code testing in IDE faster than in JShell?
What am I missing? Can someone give me a couple of use cases, where using JShell is better then using IDE? How do you guys use JShell?
回答1:
Though I would really encourage you to go ahead and read The Java Shell motivation and goals.
Yet to answer your question with a slight hands-on and I would actually be glad to know about the time you take and procedure you would follow while trying this out on an IDE. So, with few those, here you go:-
1. I recently got to know that Java 9 introduced overloaded Convenience Factory Methods for Collections and then was curious about what do they do and how do I make use of them.
Steps
-> Type 'jshell' on command prompt (assuming JAVA_HOME is set to JDK9's bin)
-> Type 'List.o'
-> Press Tab (completes the `of`)
-> Tab displays all signatures
-> Tab starts reading the documentation from first
2. How about persisting the syntax of the code? If you would have noticed in the above image the initialization of the List
didn't even bother to care about the variable to store it in, terminating semi-colon etc.
3. How quickly can you find out the exceptions thrown by some piece of code that you are about to implement? So, a use case here, I want to create a Map
of String(name of fruits) to String(their color), then add some more fruits to it in the later phase and leave out those colors which I am not certain about. Then finally get a list of all those fruits which are Red. And of course, since I am learning Java 9 these days, I would try to use as much of APIs as from Java9.
And while you would try adding all of that(^^) code in your IDE, you can yourself notice the time you would eventually take to realize all those characteristics of Immutable Map Static Factory Methods.
PS:
Robert has presented Jshell here which is a detailed view of how all can the JShell be effective.
As you do all of the above, do keep in mind that it's not a goal of Jshell to be an IDE.
And all of that, in general, does simple experimentation with a language by bypassing the compile stage of the "code -> compile -> execute" cycle. read-eval-print-loop
来源:https://stackoverflow.com/questions/46981484/why-and-how-do-you-use-jshell