我有一个代码:
public class App {
public static void main(String[] args) {
System.out.println("Hello World from main!");
JShell shell = JShell.builder().build();
shell.eval("System.out.println(\"Hello World from JShell!\");");
}
}现在我希望我可以只为JShell而不是普通代码设置输出流。
我试过了:
shell.eval("System.setOut(new Printer());");
shell.eval("System.out.println(\"Hello World!\");");但是不起作用!
我的打印机类:
class Printer extends PrintStream{
public Printer() {
super(System.out);
}
@Override
public void print(String s) {
super.print("Message: - " + s);
}
}发布于 2021-05-08 13:41:55
首先,您需要让JShell使用“本地”executionEngine,这样您才能访问Printer
JShell shell = JShell.builder().executionEngine("local").build();这基本上意味着“相同的JVM”。
其次,记住导入Printer类,或者使用它的完全限定名,因为Printer可能不在运行JShell代码的同一个包中(我的实验中名为REPL的包)。
您的Printer类似乎不是公共的,所以您也应该将其设置为public。
https://stackoverflow.com/questions/67444290
复制相似问题