I have a code :
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!\");");
}
}
Now I want that I can set the output stream for the JShell only and not the normal code.
I tried :
shell.eval("System.setOut(new Printer());");
shell.eval("System.out.println(\"Hello World!\");");
But does not work!
My Printer class:
class Printer extends PrintStream{
public Printer() {
super(System.out);
}
@Override
public void print(String s) {
super.print("Message: - " + s);
}
}
First, you need to make JShell use the "local"
executionEngine
, so that you have access to yourPrinter
:This basically means "the same JVM".
Second, remember to import the
Printer
class, or use its fully qualified name, becausePrinter
is probably not in the the same package as where JShell code is running (a package calledREPL
from my experiments).It seems like your
Printer
class is not public, so you should make itpublic
as well.