Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách import thư viện bên ngoài trong JShell Java 9

JShell là công cụ tương tác để học ngôn ngữ Java và tạo mẫu nguyên mẫu (prototyping) mã Java. JShell làm việc bằng cách đánh giá các lệnh người dùng nhập vào. Công cụ này hoạt động dựa trên nguyên tắc REPL (Read-Evaluate-Print-Loop).

Mặc định, JShell tự động import một số package Java hữu ích khi phiên bắt đầu. Gõ lệnh /imports để xem danh sách các import này.

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.*
| import javax.mail.internet.InternetAddress

Import thư viện bên ngoài

Để import thư viện bên ngoài (external libraries) trong JShell, thực hiện các bước sau:

Nếu muốn tạo đối tượng InternetAddress nằm trong package javax.mail.internet, cần import package đó trong JShell.

jshell> import javax.mail.internet.InternetAddress
| Error:
| package javax.mail.internet does not exist
| import javax.mail.internet.InternetAddress;
| ^---------------------------------^

Chỉ import class không hoạt động vì package không nằm trong classpath. Cần thêm jar hoặc file class vào classpath bằng lệnh: "/env --class-path <jars, class files>"

jshell> /env --class-path \Users\user\mail-1.4.7.jar
| Setting new options and restoring state.
jshell> import javax.mail.internet.InternetAddress

Cuối cùng, tạo đối tượng InternetAddress:

jshell> InternetAddress from = new InternetAddress("a@a")
from ==> a@a