Wednesday 20 January 2021

jshell: working with CLASSPATH

Using /env command we can set the classpath.

 

Syntax

/env -class-path {LIBRARY_PATH}

 

Example

/env -class-path /Users/Shared/gson-2.8.2.jar

 

Let's set gson library to classpath and serialize an Employee instance.

 

Step 1: Open terminal and execute jshell command.

$jshell
|  Welcome to JShell -- Version 10.0.2
|  For an introduction type: /help intro

jshell>

Step 2: Set gson library to classpath.

/env -class-path /Users/Shared/gson-2.8.2.jar

jshell> /env -class-path /Users/Shared/gson-2.8.2.jar
|  Setting new options and restoring state.

jshell>


Step 3: Import Gson class.

import com.google.gson.Gson;

jshell> import com.google.gson.Gson;

jshell>


Step 4: Define Employee class.

public class Employee {
	public int id;
	public String firstName;
	public String lastName;

}

jshell> public class Employee {
   ...>     public int id;
   ...>     public String firstName;
   ...>     public String lastName;
   ...> 
   ...> }
|  created class Employee


Step 5: Execute following statements to initialize Employee object.

Employee emp = new Employee()

emp.id = 1

emp.firstName = "Sailu"

emp.lastName = "Dokku"

 

jshell> Employee emp = new Employee()
emp ==> Employee@64bfbc86

jshell> emp.id = 1
$4 ==> 1

jshell> emp.firstName = "Sailu"
$5 ==> "Sailu"

jshell> emp.lastName = "Dokku"
$6 ==> "Dokku"


Step 6: Get an instance of Gson.

Gson gson = new Gson();

jshell> Gson gson = new Gson();
gson ==> {serializeNulls:false,factories:[Factory[typeHier ... 26a3],instanceCreators:{}}


Step 7: Serialize Employee object using gson.

gson.toJson(emp)

jshell> gson.toJson(emp)
$8 ==> "{\"id\":1,\"firstName\":\"Sailu\",\"lastName\":\"Dokku\"}"








 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment