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

Cách debug JShell trong Java 9

JShell là REPL tool chạy snippet không cần class/main. Lệnh /debug bật/tắt chế độ debug – hiển thị thông tin biên dịch, load class nội bộ của JShell implementation.

Bật debug mode

jshell> /debug
| Debugging on

Ví dụ 1: Đơn giản 5+3

jshell> 5+3
Compiling: 5+3
Kind: EXPRESSION_STATEMENT -- 5 + 3;
compileAndLoad [Unit($1)]
++setCompilationInfo()
Snippet:VariableKey($1)#11-5+3
package REPL;
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.*;
class $JShell$11 {
    public static int $1;
    public static Object do_it$() throws Throwable {
        return $1 = 5+3;
    }
}
-- diags: []
setStatus() Snippet:VariableKey($1)#11-5+3 - status: VALID
compileAndLoad ins = [Unit($1)]
-- legit = [Unit($1)]
Compiler generating class REPL.$JShell$11
compileAndLoad [Unit($1)] -- deps: [] success: true
recordCompilation: Snippet:VariableKey($1)#11-5+3 -- status VALID, unresolved []
$1 ==> 8

Ví dụ 2: Khai báo biến String

jshell> String s = "Adithya"
Compiling: String s = "Adithya";
Kind: VARIABLE -- String s = "Adithya"
compileAndLoad [Unit(s)]
++setCompilationInfo()
Snippet:VariableKey(s)#12-String s = "Adithya";
package REPL;
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 static REPL.$JShell$11.$1;
class $JShell$12 {
    public static String s;
    public static Object do_it$() throws Throwable {
        String s_ = "Adithya";
        return s = s_;
    }
}
-- diags: []
setStatus() Snippet:VariableKey(s)#12-String s = "Adithya"; - status: VALID
compileAndLoad ins = [Unit(s)] -- legit = [Unit(s)]
Compiler generating class REPL.$JShell$12
compileAndLoad [Unit(s)] -- deps: [] success: true
recordCompilation: Snippet:VariableKey(s)#12-String s = "Adithya"; -- status VALID, unresolved []
s ==> "Adithya"

Tắt debug mode

jshell> /debug
| Debugging off

Thông tin debug hiển thị

  • Quá trình compile: source code generated, imports, wrapper class.
  • Diagnostics (errors/warnings).
  • Compilation status: VALID/INVALID.
  • Class generation: tên class động REPL.$JShell$N.
  • Dependency tracking giữa snippet.

Khi nào dùng /debug?

  • Tìm hiểu JShell hoạt động nội bộ như thế nào.
  • Debug snippet phức tạp bị lỗi khó hiểu.
  • Phát triển tooling cho JShell.
  • Giáo dục: thấy Java compiler/API hoạt động real-time.

Debug mode verbose, chỉ dùng khi cần thiết. Bình thường JShell ẩn tất cả chi tiết này.