五分钟的JShell

这篇文章建立在我的My Java 9顶级功能文章的基础上,通过对这些功能的深入研究。 在这里,我们向您展示如何在五分钟内学习jshell并改善Java 9开发经验。

入门

假设您已经下载并安装了Java 9,则可以通过键入以下内容启动Shell:

jshell

或者,如果您要冗长,

C:\jdk9TestGround>jshell -v
| Welcome to JShell -- Version 9
| For an introduction type: /help intro
 
jshell>

变数

只需键入变量,带或不带分号–

jshell> int i = 1;
i ==> 1
| created variable i : int

未分配的值会自动分配给以$开头的变量–

jshell> "Hello World"
$1 ==> "Hello World"
| created scratch variable $1 : String

这意味着我们以后可以重用该值–

jshell> System.out.println($1);
Hello World

控制流程

jshell的下一步是使用控制流(如果……则为……)。 我们可以通过输入条件,对每个新行使用return来做到这一点–

jshell> if ("Hello World".equals($1)) {
 ...> System.out.println("Woohoo my if condition works");
 ...> }
Woohoo my if condition works

快速提示是使用TAB进行代码完成

方法

我们可以用与流程控制类似的方式声明一个方法,然后按

对于每个新行–

jshell> String helloWorld() {
 ...> return "hello world";
 ...> }
| created method helloWorld()

然后叫它–

jshell> System.out.println(helloWorld());
hello world

我们还可以更改外壳中的方法,并使用尚未定义的方法调用方法-

jshell> String helloWorld() {
 ...> return forwardReferencing();
 ...> }
| modified method helloWorld(), however, it cannot be invoked until method forwardReferencing() is declared
| update overwrote method helloWorld()

现在我们修复方法–

jshell> String forwardReferencing() {
 ...> return "forwardReferencing";
 ...> }
| created method forwardReferencing()
| update modified method helloWorld()

班级

我们还可以在jshell中定义类–

jshell> class HelloWorld {
 ...> public String helloWorldClass() {
 ...> return "helloWorldClass";
 ...> }
 ...> }
| created class HelloWorld

并分配和访问它们-

/env

有用的命令

现在我们有了基本知识,这里有一些快速命令–

标签 代码完成
/ vars 当前shell中的变量列表
/方法 当前shell中的方法列表
/清单 jshell会话中的所有代码段
/进口 当前在外壳进口
/方法 当前shell中的方法列表
/类型 当前的类在外壳中定义,在上述情况下,我们将看到“类HelloWorld”
/编辑 使您可以在编辑器中编辑会话(默认为JEditPad)
/出口 闭门会议

翻译自: https://www.javacodegeeks.com/2017/10/jshell-five-minutes.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值